Shutting down a WPF application from App.xaml.cs
Solution 1
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);
}
}
Solution 2
If you remove the StartupUri from app.xaml for an application with a MainWindow you need to make sure you make the following call in your OnStartup method otherwise the application will not terminate when your MainWindow closes.
this.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
@Frank Schwieterman, something along these lines may help you with your console window issue.
Rich
Software developer at yWorks GmbH. Usually I'll answer questions here about Java, C#, PowerShell, batch files, random numbers, regular expressions and Unicode. At work I primarily deal with C#, Java and JavaScript. My interests are mostly HCI, Interaction Design and UX. Recently I18n joined that list as well. That does not mean I have profound knowledge in either of those fields, just that I am interested in them. Note: People contacting me outside SO/SE is fine, but for discussing their own questions or answers SO already provides a mechanism, namely edits and comments. So please use those things first. I do hang around on Freenode as Hypftier, though.
Updated on June 12, 2020Comments
-
Rich almost 4 years
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 justthis.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
orApplication
at all.So, what is the right way to exit the program at that point, i. e. the
Startup
event handler in anApplication
object?