Link to home
Start Free TrialLog in
Avatar of alsmorris
alsmorris

asked on

The correct way to DeletObject

Hi,

I've read a ton of different info. on how to clean up bitmap objects but alot of the information is different.   Can someone explain what the correct method is for cleaning up a GDI object such as a bitmap. I.E.

HDC pDC = ::GetWindowDC(hWnd);
hBitmapDC = ::CreateCompatibleDC(pDC);
HBITMAP       hBitmap = ::LoadBitmap(hInst,(LPCTSTR)nResID);

::SelectObject(hBitmapDC,hBitmap );
::BitBlt(pDC,0,0,10,10,hBitmapDC,0,0,SRCCOPY);
                        
...How do I clean up properly?
Avatar of MattAA
MattAA

You clean up any bitmap loaded with LoadBitmap by calling DeleteObject on its handle.  If this was a pen or a brush, you would have to unselect it from the device context before you could delete it, but there shouldn't be any problems with bitmaps.  So, to cleanup after that code, you would simply put:

::DeleteObject(hBitmap);

You should also delete your memory device context (hBitmapDC) with ::DeleteDC when you are done with it.
Avatar of alsmorris

ASKER

MattAA,

I have tried this but I get resource errors... and finally the window goes black.  I am finding out that what works on 2000/XP does not work on 98.  For example what you said ::DeleteObject(hBitmap); will not give me a problem on 2000/xp but on 98 I get a black window and boundchecker tells me that the object is still selected in the DC.

Thanks :)
ASKER CERTIFIED SOLUTION
Avatar of _corey_
_corey_

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ok ... I think I figured it out...But I'm not sure this is the best way to do it...

HDC pDC = ::GetWindowDC(hWnd);
hBitmapDC = ::CreateCompatibleDC(pDC);
HBITMAP      hBitmap = ::LoadBitmap(hInst,(LPCTSTR)nResID);

HBITMAP hOld = ::SelectObject(hBitmapDC,hBitmap );

::BitBlt(pDC,0,0,10,10,hBitmapDC,0,0,SRCCOPY);

::SelectObject(hBitmapDC,hOld);
::DeleteObject(hBitmap);
::DeleteDC(hBitmapDC);




That's about how DC/Object stuff goes.  You really need to keep it nicely cleared up for 98/etc because, if I'm not mistaken after this long, there are limited DC and GDI handles.
Actually, just repeating the SelectObject(hBitmapDC, hBitmap) call should restore by itself.