HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How do I exit a WPF application programmatically?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howwpfexitprogrammaticallyapplication

Problem

How is one supposed to exit an application such as when the user clicks on the Exit menu item from the File menu?

I have tried:

this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();


Among many others. Nothing works.

Solution

To exit your application you can call

System.Windows.Application.Current.Shutdown();


As described in the documentation to the Application.Shutdown method you can also modify the shutdown behavior of your application by specifying a ShutdownMode:

Shutdown is implicitly called by Windows Presentation Foundation (WPF) in the following situations:

  • When ShutdownMode is set to OnLastWindowClose.



  • When the ShutdownMode is set to OnMainWindowClose.



  • When a user ends a session and the SessionEnding event is either unhandled, or handled without cancellation.



Please also note that Application.Current.Shutdown(); may only be called from the thread that created the Application object, i.e. normally the main thread.

Code Snippets

System.Windows.Application.Current.Shutdown();

Context

Stack Overflow Q#2820357, score: 919

Revisions (0)

No revisions yet.