C++ – Can the HWND from CreateWindow/CreateDialog be GetMessage’d from another thread

cmultithreadingwinapiwindows

Using the Win32 APIs, is it possible to create a Window or Dialog in one thread then collect events for it from another thread?

Are HWNDs tied to threads?

Trying the contrived example below I never see GetMessage() fire.

HWND g_hWnd;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) 
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}

But here, I do.

HWND g_hWnd;
HINSTANCE g_hInstance;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);

    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) 
{
    g_hInstance = hInstance;
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}

Can somebody explain what I'm seeing?

Best Answer

No.

GetMessage returns messages on the current thread's input queue. The HWND parameter is a filter, so that GetMessage only returns messages in the current thread's input queue intended for that window.

Windows have thread affinity - messages intended for a window get handled on the thread that created and therefore owns the window.