Search code examples
c++oopwinapimessage-pump

Separate window message pumps and receiving WM_QUIT


I'm trying to create independent window wrapper classes for my project. It's mostly working but cannot figure out how to get WM_QUIT in my main message pump. In the interest of learning Windows, I don't want to use other libraries for this.

This is a quick example of whats happening.

#include <iostream>
#include <Windows.h>

void TestPump()
{
    MSG msg = { 0 };

    PostQuitMessage(0);
    std::cout << "Posted WM_QUIT" << std::endl;

    while (true)
    {
        BOOL result = PeekMessage(&msg, (HWND) -1, 0, 0, PM_REMOVE);

        std::cout << "PeekMessage returned " << result << std::endl;

        if (result == 0)
            break;

        if (WM_QUIT == msg.message)
            std::cout << "got WM_QUIT" << std::endl;
    }
}

void MakeWindow()
{
    auto hwnd = CreateWindowEx(0, "Button", "dummy", 0, 0, 0, 32, 32, NULL, NULL, NULL, NULL);
    std::cout << std::endl << "Created Window" << std::endl << std::endl;
}

int main()
{
    TestPump();
    MakeWindow();
    TestPump();

    std::cin.get();

    return EXIT_SUCCESS;
}

The PeekMessage documentation is here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644943(v=vs.85).aspx

I haven't been able to find any examples of using a -1 HWND filter, but MSDN says that it'll receive thread messages where the HWND is NULL (I've checked that this is true for WM_QUIT), which I believe PostQuitMessage does with WM_QUIT.

The problem only occurs if I create a Window.

Is there anything I'm doing wrong, or are there better methods?


Solution

  • The problem appears to be with the way WM_QUIT and PostQuitMessage() operates. You can find information here:

    Why is there a special PostQuitMessage function?.

    In short, the WM_QUIT message will not be received while the queue is non-empty. Even if you filter out other messages by using a -1 HWND, the queue is still non-empty, and thus WM_QUIT is not returned. Creating of a window results in multiple HWNDs being created.