How to exit a WPF app programmatically?

In the few years I've been using C# (WinForms), I've never used WPF. But, now I love WPF, but I don't know how I am supposed to exit my application 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.


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, ie normally the main thread.


    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 as follows:

    Environment.Exit(0)
    

    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 doc for more details on how to do this)

    链接地址: http://www.djcxy.com/p/8912.html

    上一篇: 最经济的方式来显示wpf格式的富文本?

    下一篇: 如何以编程方式退出WPF应用程序?