If you create a new WPF application project with VisualStudio, you get some basics for free. Well… almost for free. The price you pay is that you might not know what’s going on behind the scenes.

Don’t get me wrong. The default behavior works just fine for most simple applications, but there are some issues you might face when you’re trying to do something more sophisticated. The default behavior of an application is to simply quit as soon as the last window is closed. Works fine when you have a main window and some dialogs on top of that. But what if you want a login dialog BEFORE your main window is shown? Well. Tough luck. As soon as your login dialog is closed, your application shuts down.

Of course there are ways to customize this behavior, but you have to know how – as usual.

The first thing you have to do is set the ShutdownMode to “OnExplicitShutdown”. You can do this either directly in your App.xaml

<Application x:Class="MyApp.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    ShutdownMode="OnExplicitShutdown">

or alternatively in the code, for example in the OnStartup method of your application

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
}

This way, your application will only terminate if you explicitly call the Application.Current.Shutdown(); method. Of course, this also means, that if you “forget” to call the shutdonw method, you application won’t terminate.

Another way to customize the application behavior is to directly change the Main method. But wait… there is no Main method… Actually, there is. If you compile your project and go to the obj folder, you will find an “App.g.cs” file with generated code that contains something like this

/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main() {
   MyApp.App app = new MyApp.App();
   app.InitializeComponent();
   app.Run();
}

Of course you can’t (or better: shouldn’t) edit the generated code. Your changes would be overwritten the next time you compile your project. Instead, what you have to do is to change the “Build Action” of your App.xaml from “ApplicationDefinition” to “Page”. This way, the Main method will not be generated automatically and you can write your own.

Leave a Reply

Your email address will not be published.

*