GDI Leak Problem

cgdi+winapi

I noticed using task manager that the following code has a GDI leak in it. The count of GDI object in the process executing this code increases by 1 each time it executes however I can't seem to find the problem.

Any help would be appreciated.

// create new DC based on current    
HDC hDC = CreateCompatibleDC(GetDC());
// select a bitmap into the new DC and keep the old one
HGDIOBJ hOldObj = SelectObject (hDC,hBM);
// do somthing here --> 100% no leak here
SomeFunction (hDC);
// select the old object back from whence it came and delete whats returned   
DeleteObject (SelectObject (hDC,hOldObj));
// delete the DC
DeleteDC(hDC);
// delete the tmp object
DeleteObject (hOldObj);

RM

Best Answer

Copying from the comment, I didn't put it as answer as I can't test it and I was not sure if it was correct, please test it.

In general it is not a good idea to have nested calls ie

HDC hDC1 = GetDC(); 
HDC hDC2 = CreateCompatibleDC(hDC1); 
.. 

instead of

HDC hDC = CreateCompatibleDC(GetDC()); 

(BTW in your code the HDC returned by GetDC is not released.)

Related Topic