Search code examples
c++winapigdi

How does GDI::DeleteObject exactly work


According to MSDN

The DeleteObject function deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system resources associated with the object. After the object is deleted, the specified handle is no longer valid.

So one(myself) would think that once DeleteObject is executed, the HANDLE is no longer valid. but what happens to the objects retrieved by ::GetObject() once i delete the object before saving them with other WinAPI calls?

        HFONT hFont = reinterpret_cast<HFONT>(::SendMessage(hwndCtrl, WM_GETFONT, 0, 0));
        if (nullptr == hFont)
        {
            LOG_ERROR(L"Invalid font specified");
            return false;
        }

        LOGFONT font = { 0 };
        if (0 == ::GetObject(hFont, sizeof(font), &font))
        {
            LOG_ERROR(L"Failed getting font");
            return false;
        }

        font.lfHeight = nSize;



       ::DeleteObject(hFont);
        HFONT hFontEx = ::CreateFontIndirect(&font);
        LPARAM lparam = MAKELPARAM(TRUE, 0);
        WPARAM wparam = (WPARAM)(hFontEx);
        SendMessage(hwndCtrl, WM_SETFONT, wparam, lparam);

As in the following example, if i decide to delete my HFONT, before sending the new message via SendMessage, i'd retrieve some unexpected results, where other controls gets their font changed, as if i'd generated some kind of a handle leak.


Solution

  • So one(myself) would think that once DeleteObject is executed, the HANDLE is no longer valid. but what happens to the objects retrieved by ::GetObject() once i delete the object before saving them with other WinAPI calls?

    With GetObject you get a description for the object, not a new object. It remains the same after handle deletion.

    As in the following example, if i decide to delete my HFONT, before sending the new message via SendMessage, i'd retrieve some unexpected results, where other controls gets their font changed, as if i'd generated some kind of a handle leak.

    If you want to send a message with deleted HFONT, I guess the result will be the same if you send it with any other garbage.