How to detach HBITMAP from GDI+ Bitmap?

80 Views Asked by At

I'm trying to create an HBITMAP from a GDI+ Bitmap, and whilst this works, as soon as the Bitmap goes out of scope the HBITMAP become invalid, too.

How can I detach the HBITMAP from the original GDI+ Bitmap, so that I'm free to move the HBITMAP around in my program?

The method currently looks like:

HBITMAP GDIBITMAPToHBitmap()
{
   int width = 500;
   int height = 500;

   //Create a bitmap
   Bitmap myBitmap(width, height, PixelFormat32bppRGB);
   Graphics g(&myBitmap);
   Gdiplus::Pen blackpen(Color(255, 0, 0, 0), 3);

   // Perform some drawing operations here

   HBITMAP myHbitmap;
   Gdiplus::Status status = myBitmap.GetHBITMAP(Color(255, 255, 255), &myHbitmap);
   return myHbitmap; // Goes out of scope on return 
}
1

There are 1 best solutions below

1
user20716902 On BEST ANSWER

So after much trial and error, I've found a solution that works. I don't know why, but at least it works.

I've found that the behaviour of GetHBITMAP() differs based on the original GDI+ Bitmap constructor that is called:

  • if Bitmap myBitmap(width, height, PixelFormat32bppRGB); is called, the resulting HBITMAP will be invalidated when myBitmap goes out of scope.

  • if using the constructor Bitmap myBitmap(tempHbitmap, nullptr); then the resulting HBITMAP remains valid, even after myBitmap is destroyed.

So, the resulting function now looks like:

HBITMAP GDIBITMAPToHBitmap(HBITMAP tempHbitmap)
{
   int width = 500;
   int height = 500;

   //Create a bitmap
   // Bitmap myBitmap(width, height, PixelFormat32bppRGB); Previously using
   Bitmap myBitmap(tempHbitmap, nullptr); // Now using

   Graphics g(&myBitmap);
   Gdiplus::Pen blackpen(Color(255, 0, 0, 0), 3);

   // Perform some drawing operations here
   g.DrawLine(&blackpen, (INT)0, 0, 250, 250);

   HBITMAP myHbitmap;
   Gdiplus::Status status = myBitmap.GetHBITMAP(Color(255, 255, 255), &myHbitmap);
   return myHbitmap; // HBITMAP no longer goes out of scope! 
}

Using this method, I'm the owner of both HBITMAPs - the temporary tempHbitmap that is passed into the function, and the returned myHbitmap.