GDI::DeleteObject 是如何工作的

How does GDI::DeleteObject exactly work

根据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.

所以一个人(我自己)会认为一旦执行了DeleteObject,HANDLE就不再有效了。但是,一旦我在使用其他 WinAPI 调用保存对象之前删除了对象,::GetObject() 检索到的对象会发生什么?

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

如以下示例所示,如果我决定删除我的 HFONT,则在通过 SendMessage 发送新消息之前,我会检索到一些意想不到的结果,其他控件的字体也会发生变化,就好像我生成了一些有点像句柄泄漏。

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?

使用 GetObject 可以获得对象的描述,而不是新对象。句柄删除后保持不变。

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.

如果你想发送删除了HFONT的消息,我想如果你发送它与任何其他垃圾,结果将是相同的。