程序缩小到托盘后系统就无法关机(解决方案)
老帅
一、解决方案
响应系统关机消息
procedure WMQUERYENDSESSION(var msg:Tmessage);message WM_QUERYENDSESSION;
procedure TFormTray.WMQUERYENDSESSION(var msg: Tmessage);
begin
msg.Result := 1;
end;
二、原理
MSDN:
The WM_QUERYENDSESSION message is sent when the user chooses to end the session or when an application calls one of the system shutdown functions. If any application returns zero, the session is not ended. The system stops sending WM_QUERYENDSESSION messages as soon as one application returns zero.
当结束对话或者一个程序调用系统关闭功能的时候,WM_QUERYENDSESSION消息会被发送给尚未终止的所有窗口。当程序在处理这个消息的时候,如果返回了false(0),那么系统将不结束对话或者关机(注销)。
Windows在关机的时候会向所有顶层窗口广播一个消息WM_QUERYENDSESSION,其lParam参数可以区分是关机还是注销用户(注销用户时lParam是ENDSESSION_LOGOFF)。然后Windows会等到所有的应用程序都对这个消息返回TRUE才会关机,因此,只要我们的应用程序对这个消息的处理返回FALSE,Windows就不会关机了。而且通过这个例子,大家也应该可以区分系统关机和注销用户了。
LRESULT CALLBACK WndProc (HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { switch (iMsg) { case WM_DESTROY : PostQuitMessage (0) ; return 0 ; case WM_QUERYENDSESSION: //关机前,做点保护数据的操作 return 1;//返回1则可以结束程序 } return DefWindowProc (hwnd, iMsg, wParam, lParam) ; } }
关于lParam参数的值:
ENDSESSION_CLOSEAPP0x00000001
The application is using a file that must be replaced, the system is being serviced, or system resources are exhausted. For more information, see Guidelines for Applications.
ENDSESSION_CRITICAL
0x40000000
The application is forced to shut down.
ENDSESSION_LOGOFF
0x80000000
The user is logging off.
更多信息:http://msdn.microsoft.com/en-us/library/windows/desktop/aa376890(v=vs.85).aspx