c++gdi+hbitmap

How to detach HBITMAP from GDI+ Bitmap?


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 
}

Solution

  • 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:

    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.