Irbis
Irbis

Reputation: 1491

winapi - FindWindow vs HCBT_CREATEWND

I need to find HWND for the context menu. I create a context menu as in this tutorial but without submenus. I can use FindWindow function this way:

HWND hWndMenu = FindWindow(TEXT("#32768"), NULL);

I can also use the WH_CBT hook. Here is the hook procedure:

LRESULT CALLBACK HookProc(int code, WPARAM wParam, LPARAM lParam)
{
    if (code == HCBT_CREATEWND)
    {
        HWND hwnd = (HWND)wParam;
        WCHAR name[1024] = { 0 };
        GetClassName(hwnd, name, sizeof(name));

        if (wcscmp(name, L"#32768"))
        {
            HWND hwndMenu = FindWindow(TEXT("#32768"), NULL);
            std::cout << "HCBT_CREATEWND hwnd: " << hwnd << std::endl;
            std::cout << "FindWindow hwnd: " << hwndMenu << std::endl;
        }
    }

    return code < 0 ? CallNextHookEx(myHook, code, wParam, lParam) : 0;
} 

When I open context menu I get two different hwnd's. I don't understand why. Could you explain it ?

Upvotes: 0

Views: 234

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595402

At the time the WH_CBT hook is called, the menu window is still in progress of being created but is not yet available to FindWindow(). So, you end up finding another unrelated menu window that exists elsewhere. That is why you are seeing different HWNDs.

Upvotes: 1

Related Questions