资源泄漏 - 设备上下文太多

时间:2015-04-16 11:17:16

标签: c++ winapi windows-7-x64

我有一个(通常)工作的C ++ / Windows程序,我注意到它有图形资源泄漏。我使用了GDIView并将其追溯到设备上下文的构建。

进一步观察我将它追踪到一对线(见注释" A线和34号线;"线B")如下:

hdc = BeginPaint(hwnd,&global_paintstruct);

handle_of_source_device_context = CreateCompatibleDC(GetDC(0)); // Line A

#if 0 // temporarily while debugging
// stuff using handle_of_source_device_context
#endif

DeleteDC(handle_of_source_device_context); // Line B
EndPaint(hwnd,&global_paintstruct);

如果我评论A&线B然后没有资源泄漏。

我测试了DeleteDC返回1.

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

当不再需要DC以防止GDI泄漏时,您需要为DC调用ReleaseDC。代码的固定版本如下所示:

hdc = BeginPaint(hwnd,&global_paintstruct);

HDC hWndDC = GetDC(NULL);
handle_of_source_device_context = CreateCompatibleDC(hWndDC); // Line A

#if 0 // temporarily while debugging
// stuff using handle_of_source_device_context
#endif

ReleaseDC(hWndDC);
ReleaseDC(handle_of_source_device_context);
DeleteDC(handle_of_source_device_context); // Line B
EndPaint(hwnd,&global_paintstruct);

答案 1 :(得分:2)

关于GetDC的返回值调用ReleaseDC:

dc = GetDC(0)
...
ReleaseDC(dc);
相关问题