为什么在关闭程序之前没有出现MessageBox
- 在窗口过程完成并观察其调用条件之后?只有在之前调用它时才会出现PostQuitMessage
。
#include <windows.h>
//#include <cstdio>
long __stdcall WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
if (uMsg == WM_CLOSE)
PostQuitMessage(0);
else if (!FindWindowExA(nullptr,nullptr,"TargetAppClass",nullptr))
PostQuitMessage(1);
return DefWindowProcA(hWnd, uMsg, wParam, lParam);
}
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, int nCmdShow) {
(void) hPrevInstance;
(void) lpCmdLine;
(void) nCmdShow;
WNDCLASSEXA WinClass;
memset(&WinClass,0,sizeof(WNDCLASSEXA));
WinClass.cbSize = sizeof(WNDCLASSEXA);
WinClass.hInstance = hInstance;
WinClass.lpfnWndProc = WindowProc;
WinClass.lpszClassName = "MonitoringApp";
CreateMutexA(NULL, TRUE, WinClass.lpszClassName);
if (ERROR_ALREADY_EXISTS == GetLastError()) return ERROR_ALREADY_EXISTS;
RegisterClassExA(&WinClass);
auto win = CreateWindowExA(0,WinClass.lpszClassName,WinClass.lpszClassName,0,0,0,0,0,nullptr,nullptr,WinClass.hInstance,nullptr);
MSG msg;
while(GetMessageA(&msg,win,0,0)) {
TranslateMessage(&msg);
DispatchMessageA(&msg);
}
// printf("%u, %u\n",msg.message,msg.wParam); // показывает 18, 1 (WM_QUIT и код выхода)
if (msg.wParam) // MessageBox не выводится. Почему?
MessageBoxA(nullptr, "Seems that the TargetApp crashed", "Monitoring App", MB_ICONWARNING | MB_OK | MB_SYSTEMMODAL);
return 0;
}
在你的窗口程序是歪曲的。
PostQuitMessage(1);
在处理每个非WM_CLOSE
消息时调用。GetMessageA
一旦它到达发送的第一个消息就中断WM_QUIT
,但其余的继续位于消息队列中并打破内部消息的循环MessageBoxA
,导致它立即返回。至少添加一些线程的标志: