【问题标题】:GetMessage/PeekMessage - remove all messages in message queueGetMessage/PeekMessage - 删除消息队列中的所有消息
【发布时间】:2017-04-05 05:39:24
【问题描述】:

我有以下代码

SendApp,点击按钮[X],执行如下代码

HWND pHWndReceiveApp = FindWindowA(NULL, "ReceiveApp");
    if (NULL == pHWndReceiveApp)
    {
        MessageBox(0, MSG_FAIL, CAPTION, 0);
        return;
    }
    for (int i = 0; i < 7; i++)
    {
        PostMessageA(pHWndReceiveApp, 9, 9, 0);
    }
    MessageBox(0, MSG_OK, CAPTION, 0);

ReceiveApp,这只是一个接收SendApp消息的应用

int i = 0;
msg.message = 69;
while (WM_QUIT != msg.message)
{
    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) > 0)
    {
        if (msg.message == 9)
        {
            //I want to remove all messages in the message queue before increase i
            ++i;
            Sleep(1000);
        }

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

如您所见,我想在 ReceiveApp 中增加变量 i 之前删除消息队列中的所有消息。 我读了this article 并看到了

PM_REMOVE - 消息在处理后从队列中删除 PeekMessage。

我认为应该删除所有消息,但它们没有,在我按下 SendApp 中的按钮 [X] 后,ReceiveApp 中的变量 i 仍然增加 7。

那么如何删除消息队列中的所有消息?

【问题讨论】:

    标签: c++ message-queue sendmessage peekmessage


    【解决方案1】:

    我明白了。我们可以在 while 循环中使用 PeekMessage 来清除队列中的消息,如下所示

    #define ID 9
    //...
    int i = 0;
    msg.message = 69;
    
    while (GetMessage(&msg, 0, 0, 0))
    {
        if (msg.message == ID)
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            while (PeekMessage(&msg, NULL, ID, ID, PM_REMOVE) > 0) //Clear message queue!
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
            //I want to remove all message in the message queue before increase i
            ++i;
            Sleep(1000);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 2016-08-28
      • 2014-02-24
      • 2016-04-27
      • 1970-01-01
      相关资源
      最近更新 更多