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
}
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+Bitmapconstructor that is called:if
Bitmap myBitmap(width, height, PixelFormat32bppRGB);is called, the resultingHBITMAPwill be invalidated whenmyBitmapgoes out of scope.if using the constructor
Bitmap myBitmap(tempHbitmap, nullptr);then the resultingHBITMAPremains valid, even aftermyBitmapis destroyed.So, the resulting function now looks like:
Using this method, I'm the owner of both
HBITMAPs - the temporarytempHbitmapthat is passed into the function, and the returnedmyHbitmap.