本文介绍了(Windows)何时删除对象和设备上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建了一个处理内存dc中的位图并将其返回的函数

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)? */
}

我的问题是在何时何地删除位图?另外,删除windc是否会影响memdc?或memdc是纯粹创建的(并且不包含指向" windc的信息)?如果是这样,那么在创建位图和memdc之后(在任何绘画之前)删除windc是适当的.

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.

推荐答案

DeleteDC(windc);

从不.您必须致电 ReleaseDC (windc);代替.

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

::CreateCompatibleDC(windc);之后,您不需要windc,也不在乎它会发生什么.由CreateCompatibleDC返回的HDC只是派生了一些参数(取决于设备的像素表示等),而没有以任何方式引用windc.

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.

代替此:

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

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

/*DeleteDC(memdc) here? */

return bitmap;

您必须执行以下操作:

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

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

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

return bitmap;

这篇关于(Windows)何时删除对象和设备上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 21:14