How to Convert a Metafile to Image by Drag'n'Droping in a Winform
I develop a Winform Application with the framlework .NET 3.5 in C#. I would like to allow the user to drag&drop a picture from Word 2007. Basically the user open the docx, select a picture and drag&drop them to my PictureBox.
I've already done the same process with picture files from my desktop and from Internet pages but I can't go through my problem with my Metafile. I've done few researches but I didn't f开发者_开发问答ind any solutions solving my issue.
Here is what I've done on my Drag&Drop event :
private void PictureBox_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.MetafilePict)){
Image image = new Metafile((Stream)e.Data.GetData(DataFormats.MetafilePict));
}
}
I can obtain a stream with this code : (Stream)e.Data.GetData(DataFormats.MetafilePict) but I don't know how to convert it into a Metafile or better an Image object.
If you have any idea or solution, I'll be glad to read it.
Thanks,
Here is a working example of Drag n Drop from Word (not for PowerPoint and 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;
}
}
After this you can use image.Save to save picture or you can use it on picturebox or other control.
I think you need to call new Metafile(stream) as there is no method .FromStream in Metafile.
I'm still digging into he web to try different way to solve my issue. Hopefully I've found this unanswered thread talking about my problem but without any response : Get Drag & Drop MS Word image + DataFormats.EnhancedMetafile & MetafilePict :
http://www.codeguru.com/forum/showthread.php?t=456722
I work around with another io be able to copy floating Image (Image stored in Shape and not InlineShape) with Word 2003 and pasting into my winform. I can't paste the link of the second source (because of my low reputation on this website) but I'll do if someone request.
So apparently there are a common issue with the fact that you cannot access to your Metafile stored in the Clipboard and by Drag&Drop.
I still need to understand how to get my Metafile by Drag&Drop.
精彩评论