现在的位置: 首页 > 综合 > 正文

ReleaseDC和DeleteDC的区别

2018年06月09日 ⁄ 综合 ⁄ 共 1801字 ⁄ 字号 评论关闭

今天做一个小软件时需要在界面上重复绘制图形

于是写了个函数绘制图形

然后在OnPaint()里调用

发现低频率的重绘窗口还好 一旦经常重绘窗口就会出现错误

应该是内存泄露的错误

但是我发现我所有的CDC全都DeleteDC了 怎么会出现这错误了 

于是查了下MSDN

在ReleaseDC里写着

API原文

intReleaseDC(CDC*pDC);

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDC

Identifies the device context to be released.

Remarks

Releases a device context, freeing it for use by other applications. The effect of the ReleaseDCmember function depends on the device-context type. 

The application must call the ReleaseDCmember function for each call to the member function and for each call to the member function.

这里最后一句提到了

The application must call the ReleaseDCmember function for each call to the member function and for each call to the member function.

所有调用GetWindowDC和GetDC获取的DC对象必须使用ReleaseDC来释放

 

然后又查看了DeleteDC的API内容

 CDC::DeleteDC 

virtualBOOLDeleteDC();

Return Value

Nonzero if the function completed successfully; otherwise 0.

Remarks

In general, do not call this function; the destructor will do it for you. The DeleteDCmember function deletes the Windows device contexts that are associated with m_hDCin the current CDCobject. If this CDCobject is the last active device context for a given device, the device is notified and all storage and system resources used by the device are released. 

An application should not call DeleteDCif objects have been selected into the device context. Objects must first be selected out of the device context before it it is deleted. 

An application must not delete a device context whose handle was obtained by calling . Instead, it must call to free the device context. The and classes are provided to wrap this functionality. 

The DeleteDCfunction is generally used to delete device contexts created with , , or .

 

看了最后一句就可以区分什么时候调用ReleaseDC了

就是GetDC或GetWindowDC获得的DC要使用ReleaseDC释放

Create得到的DC要用Delete释放

这样就不会出现内存泄露事情了 

【上篇】
【下篇】

抱歉!评论已关闭.