#197 – Override Application Class Methods for Standard Events

We’ve already mentioned some of the main events that the Application class fires–e.g. Startup, Exit and SessionEnding.  We also showed how you can add event handlers to your Application-derived class to handle these events, using SessionEnding as our example.

Rather than adding an event handler for Application.SessionEnding to our class, we could have just overridden the OnSessionEnding method.  This is more appropriate in a class that already derives from Application.  Instead of specifying the handler in App.xaml and adding the handler to App.xaml.cs, we can just add code for the override to App.xaml.cs.

As an example, the override for OnSessionEnding could look something like this:

	public partial class App : Application
            protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
                // Always call method in base class, so that the event gets raised.

                // Place your own SessionEnding logic here

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