应用程序关闭窗口,但进程还在。
调试后发现WindowProc中
case WM_DESTROY:
PostQuitMessage(0);
break;
PostQuitMessage(0);后消息队列没有收到WM_QUIT。
原先错误的消息处理如下
while (true)
{
if (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
\\Do something else
}
}
问题出在PeekMessage的调用上,PeekMessage的原型如下
BOOL WINAPI PeekMessage(
__out LPMSG lpMsg,
__in_opt HWND hWnd,
__in UINT wMsgFilterMin,
__in UINT wMsgFilterMax,
__in UINT wRemoveMsg
);
第二个参数 HWND hWnd , MSDN给的解释如下
hWnd [in, optional]
Type: HWND
A handle to the window whose messages are to be retrieved. The window must belong to the current thread.
If hWnd is NULL, PeekMessage retrieves messages for any window that belongs to the current thread, and any messages on the current thread's message queue whose hwnd value is NULL (see the MSG structure). Therefore if hWnd is NULL, both window messages and thread messages are processed.
If hWnd is -1, PeekMessage retrieves only messages on the current thread's message queue whose hwnd value is NULL, that is, thread messages as posted by PostMessage (when the hWnd parameter is NULL) or PostThreadMessage.
意思是如果这个参数是窗口句柄,获取的是这个窗口的消息,前提是这个窗口属于当前线程。如果hWnd 是 NULL 那么PeekMessage获取所有属于当前线程的消息,包括窗口消息和线程消息(hwnd 为NULL)
如果 hWnd 是 -1, PeekMessage 仅获取hwnd为NULL的线程消息(PostMessage时hWnd参数为NULL的消息)或者PostThreadMessage发送的消息。
错误的代码仅处理的窗口消息,hwnd为NULL的消息没有处理,所以也就收不到WM_QUIT消息。更正为
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)
后问题就自然解决了。