我想知道这两个片段之间是否存在差异:
一个:
void main()
{
// ...
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
ExitProcess(0);
}
// ...
void quit()
{
PostQuitMessage(0);
}
两个:
bool quit = false;
void main()
{
// ...
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if(quit)
{
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&_msg);
}
ExitProcess(0);
}
}
// Shouldn't get here
ExitProcess(1);
}
// ...
void quit()
{
quit = true;
PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);
}
抱歉,我想不出更短的片段。
我的问题是调用 PostQuitMessage
并用 GetMessage
处理所有消息是否等同于用 PeekMessage
处理所有消息,直到它返回 FALSE
。
According to Raymond ,WM_QUIT
是“仅当消息队列为空时才生成”,因此看起来这两种方法应该做同样的事情,但也许存在细微差别。
最佳答案
Raymond 的博文说:
Because the system tries not to inject a WM_QUIT message at a "bad time"; instead it waits for things to "settle down" before generating the WM_QUIT message, thereby reducing the chances that the program might be in the middle of a multi-step procedure triggered by a sequence of posted messages.
所以理论上没有,没有区别,因为系统不会产生WM_QUIT
直到队列为空。然而,Raymond 并没有说保证消息不会在WM_QUIT
生成后到达,只是系统尝试 避免它。
因此可以想象,在您退出主 GetMessage
循环后,另一个线程可能会向您发送消息,并且根据您的应用程序,这可能是您必须处理的事情。例如,如果您使用接收线程预期释放的内存分配在内部发布消息,您可能需要一个单独的 PeekMessage
循环在线程完全退出之前清理它们。
但在实践中,没有人像您的第二个示例那样编写消息循环。
关于c - 使用 `PostQuitMessage` 和只处理所有消息有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26305865/