开发者

How to detect Windows shutdown or logoff

开发者 https://www.devze.com 2023-03-22 05:08 出处:网络
I need to detect when Windows is shutdown (or restarted) or wh开发者_StackOverflow中文版en the user is logging off. I need to properly close the application before the application is closed.

I need to detect when Windows is shutdown (or restarted) or wh开发者_StackOverflow中文版en the user is logging off. I need to properly close the application before the application is closed. I noticed that no exit application event is raised when Windows is closing day.

I read the post Is there a way in c# to detect a Windows shutdown/logoff and cancel that action (after asking the user)

but I'm not sure of where I should perform the operations before closing. Thanks.


Attach an event handler method to the SystemEvents.SessionEnding event, and your handler method will be called each time the event is raised. Handling this event will allow you to cancel the pending log off or shut down, if you wish. (Although that doesn't actually work like it sounds in current operating systems; for more information see the MSDN documentation here.)

If you don't want to cancel the event, but just react to it appropriately, you should handle the SystemEvents.SessionEnded event instead.

You must make sure that you detach your event handlers when the application is closed, however, because both of these are static events.


You can use a native solution via pinvoke if your code is not running in a non-interactive session (such as a system service):

//SM_SHUTTINGDOWN = 0x2000
bool bShutDownPending = GetSystemMetrics(SM_SHUTTINGDOWN) != 0;


Now you should use something like this:

private static int WM_QUERYENDSESSION = 0x11;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if (m.Msg==WM_QUERYENDSESSION)
    {
        MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot");
    }
    
    base.WndProc(ref m);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消