问题
Normally, if a program selects an object into a device context, or changes its properties, it should change them back before releasing the device context. What happens if it doesn't?
Let's say I do this:
HDC hdc = GetDC(some_window);
SelectObject(hdc, some_font);
SetTextColor(hdc, 0x123456);
SetBkColor(hdc, 0xFEDCBA);
SetROP2(hdc, R2_XORPEN);
ReleaseDC(some_window, hdc);
and some_window
's window class does not have the CS_OWNDC
or CS_CLASSDC
flag. What happens?
回答1:
Of the functions you listed, SelectObject
is the only one that would cause a problem if the object is not de-selected (by selecting the original object). This would cause the some_font
resource to be leaked because the DC would have been holding an open handle on it at the time it was released.
You should be doing this:
HDC hdc = GetDC(some_window);
HGDIOBJ hOldObj = SelectObject(hdc, some_font);
// ...
SelectObject(hdc, hOldObj);
ReleaseDC(some_window, hdc);
Or perhaps this:
HDC hdc = GetDC(some_window);
int nSaved = SaveDC(hdc);
SelectObject(hdc, some_font);
// ...
RestoreDC(nSaved);
ReleaseDC(some_window, hdc);
As MSDN notes :
Each of these functions returns a handle identifying a new object. After an application retrieves a handle, it must call the SelectObject function to replace the default object. However, the application should save the handle identifying the default object and use this handle to replace the new object when it is no longer needed. When the application finishes drawing with the new object, it must restore the default object by calling the SelectObject function and then delete the new object by calling the DeleteObject function. Failing to delete objects causes serious performance problems.
回答2:
The failure to restore the original font object causes a handle leak. The OS will retain the handle to some_font. If this code is executed repeatedly then another handle is leaked every time. You will see the Handles count in Task Manager building up. If this goes on for a long time there will eventually be painting failures that appear as junk.
来源:https://stackoverflow.com/questions/22279747/what-happens-if-you-release-an-unclean-device-context