biloon
biloon

Reputation: 435

(Windows) When to delete object and device context?

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.

Upvotes: 1

Views: 2235

Answers (1)

Serge Dundich
Serge Dundich

Reputation: 4429

DeleteDC(windc);

Never. You have to call ReleaseDC(windc); instead.

After ::CreateCompatibleDC(windc); you don't need windc and 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 to windc in any way.

Instead of this:

::SelectObject(memdc,(HGDIOBJ)bitmap);

//do the painting
//...
//painting done

/*DeleteDC(memdc) here? */

return bitmap;

You have to do something like this:

HGDIOBJ prevBitmap = ::SelectObject(memdc,(HGDIOBJ)bitmap);

//do the painting
//...
//painting done

::SelectObject(memdc,prevBitmap);
DeleteDC(memdc);

return bitmap;

Upvotes: 1

Related Questions