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

Mic*_*ick 0 c++ winapi windows-7-x64

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

进一步观察我将它跟踪到一对线(见注释"A行"和"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);
Run Code Online (Sandbox Code Playgroud)

如果我注释掉A和B行,那么就没有资源泄漏.

我测试了DeleteDC返回1.

有任何想法吗?

And*_*gin 6

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

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);
Run Code Online (Sandbox Code Playgroud)