public static Bitmap CopyHBitmapToBitmap(IntPtr nativeHBitmap)
        {
            // Get width, height and the address of the pixel data for the native HBitmap
            BITMAP bitmapStruct = new BITMAP();

            Gdi32.GetObjectBitmap(nativeHBitmap, Marshal.SizeOf(bitmapStruct), ref bitmapStruct);

            // Create a managed bitmap that has its pixel data pointing to the pixel data of the native HBitmap
            // No memory is allocated for its pixel data
            Bitmap managedBitmapPointer = new Bitmap(
                bitmapStruct.bmWidth, bitmapStruct.bmHeight, bitmapStruct.bmWidth * 4, PixelFormat.Format32bppArgb, bitmapStruct.bmBits);

            // Create a managed bitmap and allocate memory for pixel data
            Bitmap managedBitmapReal = new Bitmap(bitmapStruct.bmWidth, bitmapStruct.bmHeight, PixelFormat.Format32bppArgb);

            // Copy the pixels of the native HBitmap into the canvas of the managed bitmap
            Graphics graphics = Graphics.FromImage(managedBitmapReal);

            graphics.DrawImage(managedBitmapPointer, 0, 0);
            graphics.Dispose();
            // Delete the native HBitmap object and free memory
            Gdi32.DeleteObject(nativeHBitmap);

            // Return the managed bitmap, clone of the native HBitmap, with correct transparency
            return(managedBitmapReal);
        }
Example #2
0
 public static extern int GetObjectBitmap(IntPtr hObject, int nCount, ref BITMAP lpObject);