#47 – Detecting When the Windows Session is Ending

In WPF, you can detect when a user is ending their Windows session by handling the Application.SessionEnding event.  This occurs when the user is logging out of Windows or shutting down the machine.

In your event handler, you have the ability to cancel the termination of the Windows session by setting SessionEndingCancelEventArgs.Cancel to true.

 private void Application_SessionEnding(object sender, SessionEndingCancelEventArgs e)
 {
    MessageBoxResult res = MessageBox.Show("Exiting Windows will terminate this app.  Are you sure?", "End Session", MessageBoxButton.YesNo);
    if (res == MessageBoxResult.No)
    {
        e.Cancel = true;
    }
 }

Note that this event fires when Windows is exiting, but not when the application is closed in the normal manner.

On Windows 7, if your application cancels the SessionEnding event for a shutdown, Windows will inform the user that your application is preventing Windows from shutting down:

Update (Jan-2011): It’s probably cleaner to just override the OnSessionEnding method in your Application-derived class, rather than adding an event handler.

Advertisement