What exactly is going on in this Win32 messaging loop?

风流意气都作罢 提交于 2020-01-25 23:39:44

问题


What exactly is going on inside this Win32 messaging loop? I understand that TranslateMessage is converting keycodes to UTF char codes and sending the WM_CHAR event, but what is the call to PeekMessage doing exactly? Is it filtering out a certain type of message and only translating those?

// Application / Player message loop.
MSG msg;
ZeroMemory(&msg, sizeof(msg));

while(msg.message != WM_QUIT)
{
    if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

   // work happens here...
}

回答1:


Normally the message loop will use GetMessage instead of PeekMessage. The difference is that PeekMessage returns immediately. Returning either TRUE if a message was removed, or FALSE if no message was fetched. On the other hand if the queue is empty, GetMessage blocks until a message arrives.

The point is the comment stating work happens here. Presumably the author had some reason why the normal blocking message loop would not suffice. The down side of the non-blocking message loop code in the question is that it is a busy loop. It will not idle and so it will fully consume the CPU, unless there is a call to Sleep() or similar that you have excised.

In a comment you say that you actually want to pull off keyboard messages only, and just messages for a specific window. You need to call PeekMessage like this:

PeekMessage(&msg, hwnd, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)



回答2:


All it is is a nonblocking way to get messages. It checks to see if there is a message, and if there is, it takes it out of the queue and puts it in &msg.

Check the docs.

The second parameter says which window to look in. In this case, it's "all windows in the thread."

The third and fourth parameter do let you specify whether you want keyboard or mouse events, but currently is set to "all".



来源:https://stackoverflow.com/questions/15690953/what-exactly-is-going-on-in-this-win32-messaging-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!