C ++:响应Windows注销的清除操作 [英] C++: cleanup actions in response to Windows logoff
问题描述
我想捕捉Windows注销事件,以便我可以做一些清理。我的 WindowProc
看起来像这样:
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);
并且 WinMain
中的消息循环看起来像this:
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);
目的机制是 WindowProc
code> PostQuitMessage ,导致主消息循环接收 WM_QUIT
,中断循环并将程序发送到清除。当我退出程序(因此发送 WM_DESTROY
)程序创建 success.txt
,但当程序运行时,我注销(发送 WM_ENDSESSION
),但没有。
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.
我看过 WM_QUERYENDSESSION
,但 MSDN 说每个应用程序应在收到此消息后立即返回 TRUE
或 FALSE
,并延迟任何清除操作,直到它收到 WM_ENDSESSION
消息。
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."
推荐答案
WM_ENDSESSION
处理实际上不会让应用程序退出消息循环。您应该假设系统在发送 WM_ENDSESSION
消息后调用TerminateProcess。
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.
这篇关于C ++:响应Windows注销的清除操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!