#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.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #47 – Detecting When the Windows Session is Ending

  1. Pingback: #197 – Override Application Class Methods for Standard Events « 2,000 Things You Should Know About WPF

  2. Pingback: Internship day 7# at Thomson Reuters Thailand (C#: SessionEnding) | KanTae Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: