Windows 消息的优先级

发布时间 2023-08-01 14:51:34作者: 天地浮游

众所周知,windows窗口程序是基于消息的,其最底层维护者一个死循环如下:

while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{ 
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    }
}
该循环不断从消息队列中取消息进行处理。每次调用GetMessage从消息队列取一条消息,且是按照如下优先级取消息:
  • Sent messages
  • Posted messages
  • Input (hardware) messages and system internal events
  • Sent messages (again)
  • WM_PAINT messages
  • WM_TIMER messages 

只要优先级更高的消息,优先级低的消息就只能等优先级高的消息处理完毕后才能得到处理。

另外,如果使用没有明确启动一个线程处理事务的情况下,wdinsows程序只有一个主线程,所有的处理只能排队处理,如果某个消息处理时触发了其他需要等待的消息,就会造成消息死锁。