3

I have the following code

SendApp, when click button [X], the following code execute

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, This is just a app to receive SendApp message

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

So as you can see, I want to remove all message in the message queue before increase variable i in ReceiveApp. I read this article and see that

PM_REMOVE - Messages are removed from the queue after processing by PeekMessage.

I thought all the messages should be removed but they don't, variable i in ReceiveApp still increases by 7 after I press button [X] in SendApp.

So how can I remove all message in message queue?

123iamking
  • 2,387
  • 4
  • 36
  • 56

1 Answers1

1

I got it. We can use PeekMessage in a while loop to clear the message in the queue as below

#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);
    }
}
123iamking
  • 2,387
  • 4
  • 36
  • 56