Nate
Nate

Reputation: 30636

WPF Application_Startup event runs for ever unless I make a window and show it

WPF Application Shuts Down if I open a window and close it, but if I open no windows it stays running until I explicitly close it. Here is a quick sample application:

public partial class App : Application
{
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        if (e.Args.Count() != 0)
        {
            var mw = new MainWindow();
            mw.ShowDialog();
        }
    }
}

If you supply this app a command-line argument it will open a window and close down as soon as you close the window; if you don't supply an argument it will not close and must be killed via task manager.

Upvotes: 1

Views: 918

Answers (2)

devdigital
devdigital

Reputation: 34349

Check http://msdn.microsoft.com/en-us/library/system.windows.application.shutdownmode.aspx.

The default shutdown mode is OnLastWindowClose.

Upvotes: 2

Nate
Nate

Reputation: 30636

Apparently, this has to do with how WPF manages its shutdown, there is a ShutdownMode property that needs to be set:

public partial class App : Application 
{ 
    private void Application_Startup(object sender, StartupEventArgs e) 
    {
        // this makes the behavior consistant, must call App.Shutdown(0) to exit
        this.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;

        if (e.Args.Count() != 0) 
        { 
            var mw = new MainWindow(); 
            mw.ShowDialog(); 
        } 
    } 
} 

Upvotes: 0

Related Questions