hwnd = CreateWIndow(){................}
while(GetMessage(&msg,hwnd,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
消息循环这样写当然没问题, 但为什么GetMessage的第二个参数不能是窗口的句柄hWnd呢, 毕竟当前程序只有一个窗口啊? 如果是hWnd, 程序运行时没有任何问题, 但是当你将窗口关闭后会发现程序并未真正退出, 而且此时cpu占用为100%,!! ??????
MSDN中解释如下:
当GetMessage第二个参数为NULL时:
GetMessage retrieves messages for any window that belongs to the calling thread and thread messages posted to the calling thread using thePostThreadMessage function.
中文翻译:GetMessage取得 那些属于调用线程的窗口的消息 和 通过PostThreadMessage函数投递(发送)到调用线程的线程消息.
这样问题就明白了, GetMessage需要检索到WM_QUIT返回一个FALSE结束消息循环, 而WM_QUIT是通过PostQuitMessage(0){IN WM_DESTROY OF WindowProc}发送, 属于线程消息, 而非普通的窗口消息. 如果在GetMessage中用hWnd而不是NULL, 虽然WM_QUIT 消息仍会出现在程序的消息队列中,但GetMessage却无法检索到, 而且此时窗口已经被销毁了, 如果还想取得hWnd的窗口消息, 只可能发生错误( cpu占用100%, 死循环? ).
也适用于PeekMessage!!