WPF Tip: avoid App.Current.Shutdown

In your WPF application’s Exit command handler, be wary of calling App.Current.Shutdown unless you want to bypass the normal ‘Close’ process. It can result in your override of Window.OnClosing to NOT be called, and your closing-event handlers don’t get called either.

If you override the Onclosing method, don’t forget to call the base class OnClosing!

Oh – if your WindowSettings functionality is not working, check for this mistake.

Of course I’ve never done that myself. Oh no. Neeeever.


If you are going to shutdown your application in code other than within the WPF Window or Page class, you can accomplish this by posting an event to the main window which will in turn close itself. If you want code to execute at the close of your application – you can override OnClosing within your Window subclass to accomplish this.

#region OnClosing
/// <summary>
/// This is an override of the event-handler for the Closing event.
/// </summary>
protected override void OnClosingCancelEventArgs e )
    UserSettings.SaveWindowPositionIfChangedthis );
    base.OnClosinge );

This way, you can execute that code within your unit-tests and it will not try to force your running program (which may be your test-runner in this case) to shutdown – because you simply have not defined a handler for that event.

If you do want to call App.Shutdown, then you need to consider the case where it is running within a unit-test and you don’t have an App present to shutdown. In this case App.Current will be null and it would throw an exception where you try to call App.Current.Shutdown. Instead, you could code it thusly:

public void ShutdownApplication()

Here, if App.Current is null it does not make the call to the Shutdown method (as would be the case if this is running within a test-runner instead of the normal application-program).


James W. Hurst