I have been trying to create .net image objects from IPicture handles. If the image is a bitmap, there is no problem - The Image.FromHbitmap(IntPtr) method works like a charm. There is a bit of a problem if you try to pass a handle to a ‘legacy metafile’. The constructor MetaFile(IntPtr, bool) needs a handle to an enhanced metafile and fails with “Generic error in GDI+” if you pass a handle to a ‘legacy metafile’. You need to convert the legacy metafile to an enhanced metafile and pass its handle. Here comes the API
[DllImport("gdi32")]
extern static int GetMetaFileBitsEx(IntPtr handle, int size, byte[] buff);
[DllImport("gdi32")]
extern static IntPtr SetWinMetaFileBits(int size, byte[] buff, IntPtr handle, IntPtr metafile);
[DllImport("gdi32")]
extern static bool DeleteMetaFile(IntPtr handle);
GetMetaFileBitsEx parameters – handle to a legacy metafile, buffer size and buffer. If the buffer is set to null the function returns the size of the metafile, otherwise extract the metafile into the buffer and returns the size, so we do
int bufferSize = GetMetaFileBitsEx(HBitmap, 0, null);
byte[] buffer = new byte[bufferSize];
int ret = GetMetaFileBitsEx(HBitmap, bufferSize, buffer);
We no longer need the HBitmap handle, so we have to release the memory -
DeleteMetaFile(HBitmap);
We are now ready to create the enhanced metafile -
IntPtr enhancedMeta = SetWinMetaFileBits(bufferSize, buffer, IntPtr.Zero, IntPtr.Zero);
Metafile enhancedMetaFile = new Metafile(enhancedMeta, true);