Win32消息传递循环中到底发生了什么? [英] What exactly is going on in this Win32 messaging loop?

查看:104
本文介绍了Win32消息传递循环中到底发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Win32消息传递循环中到底发生了什么?我知道TranslateMessage正在将键代码转换为UTF字符代码并发送WM_CHAR事件,但是对PeekMessage的调用到底在做什么呢?它会过滤掉某种类型的消息并仅翻译这些消息吗?

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...
}

推荐答案

通常,消息循环将使用GetMessage而不是PeekMessage.区别在于PeekMessage立即返回.如果删除了一条消息,则返回TRUE;如果未提取任何消息,则返回FALSE.另一方面,如果队列为空,则GetMessage会阻塞直到消息到达.

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.

重点是评论,指出工作在这里发生.大概作者有一定的理由为什么正常的阻塞消息循环不够用.问题中非阻塞消息循环代码的缺点是它是一个忙循环.除非您调用了Sleep()或类似的调用,否则它将不会空闲,因此将完全消耗CPU.

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.

在注释中,您说您实际上只想提取键盘消息,而只想提取特定窗口的消息.您需要像这样调用PeekMessage:

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)

这篇关于Win32消息传递循环中到底发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆