2015-04-16 79 views
0

我有一個(一般)工作的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); 

如果我註釋掉線A & B,則沒有資源泄漏。

我測試了DeleteDC返回1.

任何想法?

+3

我認爲您必須釋放GetDC返回的句柄。 – Jasper

+0

所以你呢。它在[文檔](https://msdn.microsoft.com/en-us/library/windows/desktop/dd144871.aspx)中提到:「使用公共DC繪製後,必須調用ReleaseDC函數以釋放DC「。 – Wintermute

+0

你也可以使用WTL智能指針:CClientDC和DC – Eugene

回答

6

你需要調用ReleaseDC爲直流時,不再需要防止GDI泄漏。您的代碼的固定版本將如下所示:

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); 
2

呼叫ReleaseDC上的GetDC的返回值:

dc = GetDC(0) 
... 
ReleaseDC(dc);