消息循环(Message loop)学记 GetMessage TranslateMessage DispatchMessage


看到下面一段代码 不清楚什么意思

MSG  msg
while( GetMessage(&msg,NULL,0,0) )
{
 TranslateMessage (&msg);
 DispatchMessage(&msg);
}

GetMessage函数第一 个参数是用来获取MSG结构的指针。第二个参数是一个窗口句柄(HWND),用来获取指定窗口的消息,填 NULL表示获取当前线程所有窗口的消息或者线程消息(Thread message)。最后两个参数是 wMsgFilterMin和wMsgFilterMax,用来获取指定的消息,当都填0则表示获取所有的消息。

MSDN:http://msdn.microsoft.com/zh-cn/library/ms644936(v=vs.110)
TranslateMessage函数根据WM_KEYUP,WM_KEYDOWN之类的时间,生成相应的WM_CHAR之类的消息。

msdn:http://msdn.microsoft.com/en-us/library/ms644955(VS.85).aspx
DispatchMessage函数将窗口消息,交给相应的窗口过程(WindowProc)来处理。

msdn:http://msdn.microsoft.com/en-us/library/windows/desktop/ms644934(v=vs.85).aspx


但是上面的程序是不推荐的,在msdn上面关于GetMessage的return value的时候已经提到,推荐下面的写法:

BOOL bRet;

while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
{ 
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    }
}
原因如下:
 
Return value
Type:
Type: BOOL
If the function retrieves a message other than WM_QUIT, the return value is nonzero.
If the function retrieves the WM_QUIT message, the return value is zero.
If there is an error, the return value is -1. For example, the function fails if hWnd is an invalid window handle or lpMsg is an invalid pointer. To get extended error information, call GetLastError.

也就是说除了退出时候返回0之外,如果发生错误(句柄或消息无效),将返回-1,可以通过
GetLastError来获得具体原因。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值