开发者

(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 an开发者_如何学Cy painting) is appropriate.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜