PeekMessage和GetMessage函数的主要区别

经网络资料查找以及MSDN资源查找,整合出PeekMessage函数和GetMessage函数的主要区别,内容比较全,也有应用代码说明。

联系:

在Windows的内部,GetMessage和PeekMessage执行着相同的代码,Peekmessage和Getmessage都是向系统的消息队列中取得消息,并将其放置在指定的结构。

区别:

PeekMessage:
有消息时返回TRUE,没有消息返回FALSE, 不区分该消息是否为WM_QUIT。

GetMessage :
1. 有消息时且消息不为WM_QUIT时返回TRUE;
2. 如果有消息且为WM_QUIT则返回FALSE;
3. 如果出现错误,函数返回-1;
4. 没有消息时该函数不返回,会阻塞,直到消息出现。

对于取得消息后的不同行为:

GetMessage :取得消息后,删除除WM_PAINT消息以外的消息。
PeekMessage:取得消息后,根据wRemoveMsg参数判断是否删除消息。PM_REMOVE则删除,PM_NOREMOVE不删除。

函数原型和消息循环:

GetMessage说明

//函数原型
BOOL GetMessage(
  LPMSG lpMsg,         // address of structure with message
  HWND hWnd,           // handle of window
  UINT wMsgFilterMin,  // first message
  UINT wMsgFilterMax   // last message
);

//消息循环
//Because the return value can be nonzero, zero, or -1,遇到WM_QUIT退出
while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
{ 
    if (bRet == -1)
    {
        // handle the error and possibly exit,异常情况处理
    }
    else
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    }
}

PeekMessage说明

//函数原型:
BOOL PeekMessage(
  LPMSG lpMsg,         // pointer to structure for message
  HWND hWnd,           // handle to window
  UINT wMsgFilterMin,  // first message
  UINT wMsgFilterMax,  // last message
  UINT wRemoveMsg      // removal flags
);

//消息循环
while (TRUE)
{        
    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))        
    {        
          if (msg.message == WM_QUIT)        
                  break;        
           TranslateMessage (&msg);        
           DispatchMessage (&msg);        
    }        
    else        
    {        
            // 处理空闲任务        
    }       
} 

参考文章:
1. http://blog.sina.com.cn/s/blog_8a7012cf010151cr.html
2. MSDN说明文档

原文地址:https://www.cnblogs.com/jinxiang1224/p/8468271.html