Suppose I create a function that process a bitmap in memory dc and return it
HBITMAP paint (HWND hwnd)
{
HDC windc = ::GetWindowDC(hwnd);
HDC memdc = ::CreateCompatibleDC(windc);
HBITMAP bitmap = ::CreateCompatibleBitmap(windc,100,100); //Don't bother with the height and width
::SelectObject(memdc,(HGDIOBJ)bitmap);
/* DeleteDC(windc) here? */
//do the painting
//...
//painting done
/*DeleteDC(memdc) here? */
return bitmap;
/* Code does not reach here */
/* So where do I put DeleteObject(bitmap)? */
}
My question is where and when to delete the bitmap? Also, does deleting windc affect the memdc? or memdc is purely created (and does not contain information that “points” to the windc) ? If that is true, then deleting windc after bitmap and memdc are created (before any painting) is appropriate.
Never. You have to call ReleaseDC(windc); instead.
After
::CreateCompatibleDC(windc);you don’t needwindcand don’t care what happens with it. HDC returned by CreateCompatibleDC just derives some of the parameters (device dependent pixel representation, etc) but does not refer towindcin any way.Instead of this:
You have to do something like this: