0

我正在尝试为我的项目创建独立的窗口包装类。它大部分都在工作,但无法弄清楚如何在我的主消息泵中获取 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 一起使用。

仅当我创建一个窗口时才会出现此问题。

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

4

2 回答 2

0

问题似乎出在方式WM_QUITPostQuitMessage()操作上。你可以在这里找到信息:

为什么有一个特殊的 PostQuitMessage 函数?.

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

于 2017-08-24T14:50:51.847 回答
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
于 2017-08-24T13:03:20.353 回答