单独的窗口消息泵和接收WM_QUIT

时间:2017-08-24 12:02:42

标签: c++ oop winapi message-pump

我正在尝试为我的项目创建独立的窗口包装类。它主要工作,但无法弄清楚如何在我的主消息泵中获取WM_QUIT。为了学习Windows,我不想为此使用其他库。

这是发生什么事的一个简单例子。

#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;
}

PeekMessage文档位于:https://msdn.microsoft.com/en-us/library/windows/desktop/ms644943(v=vs.85).aspx

我无法找到使用-1 HWND过滤器的任何示例,但是MSDN说它会接收HWND为NULL的线程消息(我已经检查过WM_QUIT是否为真),我相信PostQuitMessage可以使用WM_QUIT。

只有在创建窗口时才会出现问题。

有什么我做错了,还是有更好的方法?

2 个答案:

答案 0 :(得分:0)

这似乎是一个有趣的案例,所以我创建了一个mcve,虽然我很难解释这种行为:

#include <Windows.h>
#include <CommCtrl.h>

#include <iostream>
#include <cassert>

void
Create_ThreadMessagePump(void)
{
    ::MSG msg;
    ::PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
    ::std::wcout << L"initialized thread message pump" << ::std::endl;
}

void
Create_Window(void)
{
    auto const hwnd{::CreateWindowExW(0, WC_STATICW, L"dummy window", 0, 0, 0, 32, 32, NULL, NULL, NULL, NULL)};
    (void) hwnd; // not used
    assert(NULL != hwnd);
    ::std::wcout << L"created window" << ::std::endl;
}

void
Test_QuitMessageExtraction(void)
{
    ::PostQuitMessage(0);
    ::std::wcout << L"posted WM_QUIT" << ::std::endl;
    for(;;)
    {   
        ::MSG msg;
        auto const result{::PeekMessageW(&msg, (HWND) -1, 0, 0, PM_REMOVE)};
        ::std::wcout << L"PeekMessageW returned " << result << ::std::endl;
        if(0 == result)
        {
            ::std::wcout << L"no more messages to peek" << ::std::endl;
            break;
        }
        if(WM_QUIT == msg.message)
        {
            ::std::wcout << L"got WM_QUIT" << ::std::endl;
        }
    }
}

int
main()
{
    //Create_ThreadMessagePump(); // does not change anything
    Test_QuitMessageExtraction();
    Create_Window();
    Test_QuitMessageExtraction();
    system("pause");
    return(0);
}

输出:

posted WM_QUIT
PeekMessageW returned 1
got WM_QUIT
PeekMessageW returned 0
no more messages to peek
created window
posted WM_QUIT
PeekMessageW returned 0
no more messages to peek

答案 1 :(得分:0)

问题似乎与WM_QUITPostQuitMessage()的运作方式有关。你可以在这里找到信息:

Why is there a special PostQuitMessage function?

简而言之,当队列非空时,将不会收到WM_QUIT消息。即使您使用-1 HWND过滤掉其他消息,该队列仍然是非空的,因此不会返回WM_QUIT。创建窗口会导致创建多个HWND。