Search code examples
c++winapivisual-c++window

Wait on HANDLE while processing messages for a specific HWND


I have a wait handle (CreateEvent) and a window handle (CreateWindow). On the UI thread, I want to process messages for that HWND only until the wait handle is signaled.

GetMessage will let me receive messages for a single window handle, but it doesn't know anything about wait handles.

MsgWaitForMultipleObjectsEx will let me wait for either the wait handle or a window message, but a message sent to any window on the current thread will unblock it -- there's no way to filter by HWND.

I can't just string those two together. If a message for a window unblocks the MsgWaitForMultipleObjectsEx call and I use GetMessage for a different HWND, the message remains in the queue, and the next MsgWaitForMultipleObjectsEx call returns immediately due to the unprocessed message. Loop ad infinitum.


Solution

  • DWORD dwRet;
    do
    {
        dwRet = MsgWaitForMultipleObjectsEx(1, &hEvent, INFINITE, QS_ALLINPUT, 0);
        if (dwRet == (WAIT_OBJECT_0+1))
        {
            while (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
        // ...
    }
    while (dwRet != WAIT_OBJECT_0);