c# - 如何在 Winform 中通过拖放将图元文件转换为图像

标签 c# .net winforms drag-and-drop metafile

我使用 C# 中的 framlework .NET 3.5 开发了一个 Winform 应用程序。 我想允许用户从 Word 2007 中拖放图片。基本上用户打开 docx,选择图片并将它们拖放到我的 PictureBox 中。

我已经对来自桌面和 Internet 页面的图片文件执行了相同的过程,但我无法解决我的 Metafile 问题。我做的研究很少,但没有找到解决我的问题的任何解决方案。

这是我在拖放事件中所做的:

 private void PictureBox_DragDrop(object sender, DragEventArgs e)
 {
    if (e.Data.GetDataPresent(DataFormats.MetafilePict)){
        Image image = new Metafile((Stream)e.Data.GetData(DataFormats.MetafilePict));     
     }
  }

我可以使用以下代码获取流:(Stream)e.Data.GetData(DataFormats.MetafilePict) 但我不知道如何将其转换为图元文件或更好的图像对象。

如果您有任何想法或解决方案,我将很乐意阅读。

谢谢,

最佳答案

这是一个从 Word 中拖放的工作示例(不适用于 PowerPoint 和 Excel):

    static Metafile GetMetafile(System.Windows.Forms.IDataObject obj)
    {
        var iobj = (System.Runtime.InteropServices.ComTypes.IDataObject)obj;
        var etc = iobj.EnumFormatEtc(System.Runtime.InteropServices.ComTypes.DATADIR.DATADIR_GET);
        var pceltFetched = new int[1];
        var fmtetc = new System.Runtime.InteropServices.ComTypes.FORMATETC[1];
        while (0 == etc.Next(1, fmtetc, pceltFetched) && pceltFetched[0] == 1)
        {
            var et = fmtetc[0];
            var fmt = DataFormats.GetFormat(et.cfFormat);
            if (fmt.Name != "EnhancedMetafile")
    {
                continue;
            }
            System.Runtime.InteropServices.ComTypes.STGMEDIUM medium;
            iobj.GetData(ref et, out medium);
            return new Metafile(medium.unionmember, true);
        }
        return null;
    }



private void Panel_DragDrop(object sender, DragEventArgs e)
 {

    if (e.Data.GetDataPresent(DataFormats.EnhancedMetafile) & e.Data.GetDataPresent(DataFormats.MetafilePict))
    {
                    Metafile meta = GetMetafile(e.Data);
                    Image image = meta;
    }
}

在此之后,您可以使用 image.Save 来保存图片,或者您可以在图片框或其他控件上使用它。

关于c# - 如何在 Winform 中通过拖放将图元文件转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4375324/

相关文章:

c# - Messenger 默认关闭端口

c# - Web API 的性能

c# - 如何在我的安装项目中嵌入横幅图像和/或添加删除程序图标?

c# - 使用带有事件的观察者模式添加新闻订阅者

c# - 获取 ComboBox 的当前索引?

c# - 在事务中使用 SqlCommand 时,我应该调用 Parameters.Clear 吗?

c# - 有什么方法可以确定 asp.net 中 CultureInfo 的文本方向吗?

c# - 为 TextBox 控件引发了哪些验证事件?

c# - 将控件添加到 Office (VSTO) 中的现有功能区组

c# - 如何在Windows窗体上有效地多线程?