Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutting down a WPF application from App.xaml.cs

I am currently writing a WPF application which does command-line argument handling in App.xaml.cs (which is necessary because the Startup event seems to be the recommended way of getting at those arguments). Based on the arguments I want to exit the program at that point already which, as far as I know, should be done in WPF with Application.Current.Shutdown() or in this case (as I am in the current application object) probably also just this.Shutdown().

The only problem is that this doesn't seem to work right. I've stepped through with the debugger and code after the Shutdown() line still gets executed which leads to errors afterwards in the method, since I expected the application not to live that long. Also the main window (declared in the StartupUri attribute in XAML) still gets loaded.

I've checked the documentation of that method and found nothing in the remarks that tell me that I shouldn't use it during Application.Startup or Application at all.

So, what is the right way to exit the program at that point, i. e. the Startup event handler in an Application object?

like image 792
Joey Avatar asked Mar 03 '09 11:03

Joey


People also ask

How do I close an application in WPF?

We can close the window either by using "this. Close()"or by using "App. Current. Shutdown()".

How do I close all Windows in WPF?

The proper way to shutdown a WPF app is to use Application. Current. Shutdown() . This will close all open Window s, raise some events so that cleanup code can be run, and it can't be canceled.

What is app xaml CS?

xaml. cs is the code-behind page for MainPage. xaml. It's where you add your app logic and event handlers. Together these two files define a new class called MainPage , which inherits from Page, in the HelloWorld namespace.


1 Answers

First remove the StartupUri property from App.xaml and then use the following:

    protected override void OnStartup(StartupEventArgs e)     {         base.OnStartup(e);          bool doShutDown = ...;          if (doShutDown)         {             Shutdown(1);             return;         }         else         {             this.StartupUri = new Uri("Window1.xaml", UriKind.Relative);         }     } 
like image 198
Jakob Christensen Avatar answered Sep 30 '22 01:09

Jakob Christensen