As you know CF v1 (it will be available in CF v2 though) doesn't provide implementaion of the FromHbitmap method that allows creation of the managed Bitmap object from native window handle (HBITMAP). The solution that I provide is based on the idea of creation of a managed Bitmap from an in memory array/stream of a bitmap file like for example is done in the XrossOne Mobile GDI+. We can get the information on the Bitmap using GetObject API including a pointer to the bitmap bits which we can copy to the managed array:
public static Bitmap FromHbitmap(IntPtr handle)
{
BITMAP bm = new BITMAP();
// Get info
GetObject(handle, Marshal.SizeOf(bm), ref bm);
// Create our Bitmap buffer
BitmapBuffer bmpBuffer = new BitmapBuffer(bm.bmWidth, bm.bmHeight, (short)bm.bmBitsPixel);
// Native pointer to bmp bits
IntPtr pBits = new IntPtr(bm.bmBits);
// Create temp array for bitmap bits to workaround a bug in the Marshal.Copy -
// it never uses the startIndex
byte[] tempBits = new byte[bm.bmWidthBytes * bm.bmHeight];
//Get the bits to the temporary managed byte array.
Marshal.Copy(pBits, tempBits, 0, bm.bmWidthBytes * bm.bmHeight);
// Copy from the temporary managed byte to our buffer
System.Buffer.BlockCopy(tempBits, 0, bmpBuffer.buffer, offset, tempBits.Length);
// Create managed Bitmap
return bmpBuffer.CreateBitmap();
}
You can download the whole implementation for the BitmapBuffer class and the sample here.
FromHbitmapProject.zip (6.63 KB)