问题
I want to catch a Windows logoff event so that I can do some cleanup. My WindowProc
looks like this:
switch (uMsg){
case WM_ENDSESSION:
case WM_DESTROY:
PostQuitMessage(0);
return 0;
// other messages
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
and the message loop in WinMain
looks like this:
for(;;){
bool bTerminate = false;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
if(msg.message == WM_QUIT){
bTerminate = true;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if(bTerminate){
break;
}
// do other stuff
Sleep(10);
}
FILE * fout;
fopen_s(&fout, "C:\\success.txt", "w"); // simulating cleanup actions
fclose(fout);
ExitProcess(0);
The intended mechanism is that WindowProc
does PostQuitMessage
, causing the main message loop to receive WM_QUIT
, breaking the loop and sending the program to cleanup. When I exit the program (thus sending WM_DESTROY
) the program creates success.txt
, but when the program is running and I log off (sending WM_ENDSESSION
), it does not.
I have looked at WM_QUERYENDSESSION
as well, but MSDN says "Each application should return TRUE
or FALSE
immediately upon receiving this message, and defer any cleanup operations until it receives the WM_ENDSESSION
message."
回答1:
WM_ENDSESSION
processing doesn't actually give your application a chance to exit the message loop. You should assume the system calls TerminateProcess after sending the WM_ENDSESSION
message.
Therefore, any clean-up your application needs to perform should be done before returning from the window procedure.
回答2:
In Windows UI applications, you can use:
LRESULT CMainDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
You can get more help from this msdn link.
{
if(message == WM_ENDSESSION)
{
if(lParam == ENDSESSION_LOGOFF)
{
/*Handle event*/
}
}
return CDialogEx::WindowProc(message, wParam, lParam);
}
来源:https://stackoverflow.com/questions/13003165/c-cleanup-actions-in-response-to-windows-logoff