Tuesday, May 13, 2008

CF_BITMAP from .Net Bitmap

This is the easiest way I know to get an in-memory device-independent bitmap ready for the clipboard.

I could not use ImageFormat.MemoryBmp because it throws an exception when saved to a stream. Therefore use .bmp and strip header.

Bitmap bitmap = RenderBitmap();
MemoryStream mem = new MemoryStream();
bitmap.Save(mem, ImageFormat.Bmp);
byte[] bmp = mem.ToArray();
int offset = Marshal.SizeOf(typeof(Win32.BITMAPFILEHEADER));
IntPtr hdib = Win32.GlobalAlloc(0x0042 /*GHND*/, mem.Length - offset);
Debug.Assert(hdib != IntPtr.Zero);
IntPtr buf = Win32.GlobalLock(hdib);
Marshal.Copy(bmp, offset, buf, (int)mem.Length - offset);
Win32.GlobalUnlock(hdib);

STGMEDIUM medium = new STGMEDIUM();
medium.pUnkForRelease = null;
medium.unionmember = hdib;
medium.tymed = TYMED.TYMED_HGLOBAL;

0 Comments:

Post a Comment

<< Home