c# - How do I exit a WPF application programmatically?

ID : 4279

viewed : 152

Tags : c#.netwpfshutdown





Top 5 Answer for c# - How do I exit a WPF application programmatically?

vote vote

92

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.

vote vote

90

If you really need it to close out you can also use Environment.Exit(), but it is not graceful at all (more like ending the process).

Use it as follows:

Environment.Exit(0) 
vote vote

74

As wuminqi said, Application.Current.Shutdown(); is irreversible, and I believe it is typically used to force an application to close at times such as when a user is logging off or shutting down Windows.

Instead, call this.close() in your main window. This is the same as pressing Alt + F4 or the close [x] button on the window. This will cause all other owned windows to close and will end up calling Application.Current.Shutdown(); so long as the close action wasn't cancelled. Please see the MSDN documentation on Closing a Window.

Also, because this.close() is cancellable you can put in a save changes confirmation dialog in the closing event handler. Simply make an event handler for <Window Closing="..."> and change e.Cancel accordingly. (See the MSDN documentation for more details on how to do this.)

vote vote

61

Use any of the following as needed:

1.

 App.Current.Shutdown(); OR  Application.Current.Shutdown(); 

2.

 App.Current.MainWindow.Close(); OR  Application.Current.MainWindow.Close(); 

Above all methods will call closing event of Window class and execution may stop at some point (cause usually applications put dialogues like 'are you sure?' or 'Would you like to save data before closing?', before a window is closed completely)

3. But if you want to terminate the application without any warning immediately. Use below

   Environment.Exit(0); 
vote vote

50

This should do the trick:

Application.Current.Shutdown(); 

If you're interested, here's some additional material that I found helpful:

Details on Application.Current

WPF Application LifeCycle

Top 3 video Explaining c# - How do I exit a WPF application programmatically?







Related QUESTION?