当用户从文件菜单中单击退出菜单项时,应该如何退出应用程序?

我试过:

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

还有很多其他的。没有什么工作。


当前回答

如果你使用application . current . shutdown()来退出应用程序,你可能会得到一个System. current . shutdown()。调用线程不能访问该对象,因为它属于另一个线程。如果从不同的线程调用它。要解决这个问题,您可以像这样包装调用

Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());

其他回答

如果你真的需要它来关闭,你也可以使用Environment.Exit(),但这一点都不优雅(更像是结束进程)。

使用方法如下:

Environment.Exit(0)

根据我的理解,Application.Current.Shutdown()也有它的缺点。

如果你想显示一个确认窗口让用户确认是否退出,Application.Current.Shutdown()是不可逆的。

我是这样做的:

// Any control that causes the Window.Closing even to trigger.
private void MenuItemExit_Click(object sender, RoutedEventArgs e)
{
    this.Close();
}

// Method to handle the Window.Closing event.
private void Window_Closing(object sender, CancelEventArgs e)
{
    var response = MessageBox.Show("Do you really want to exit?", "Exiting...",
                                   MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
    if (response == MessageBoxResult.No)
    {
        e.Cancel = true;
    }
    else
    {
        Application.Current.Shutdown();
    }
}

我只从主应用程序窗口调用application . current . shutdown(),所有其他窗口都使用this.Close()。在我的主窗口中,Window_Closing(…)处理右上角的x按钮。如果任何方法调用窗口关闭器,如果用户确认,Window_Closing(…)将捕获关闭事件。

The reason I do in fact use Application.Current.Shutdown() in my main window is that I've noticed that if a design mistake was made and I haven't declared a parent of one of my windows in an application, if that window is opened without being shown prior to the last active window closing, I'm left with a hidden window running in the background. The application will not shut down. The only way to prevent complete memory leak is for me to go into the Task Manager to shut down the application. Application.Current.Shutdown() protects me from unintended design flaws.

这是我个人的经验。最后,使用最适合您的场景的方法。这只是另一条信息。

正如wuminqi所说,Application.Current.Shutdown();是不可逆的,我相信它通常用于强制应用程序关闭时,如当用户注销或关闭Windows。

相反,在主窗口中调用this.close()。这与在窗口上按Alt + F4或关闭[x]按钮相同。这将导致所有其他拥有的窗口关闭,并最终调用Application.Current.Shutdown();只要近距离行动没有取消。请参阅MSDN文档关闭窗口。

此外,由于this.close()是可取消的,您可以在关闭事件处理程序中放入一个保存更改确认对话框。简单地为<Window Closing="…>和更改e。(有关如何做到这一点的详细信息,请参阅MSDN文档。)

要退出应用程序,您可以调用

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

如应用程序文档中所述。你也可以通过指定ShutdownMode来修改应用程序的关机行为:

在以下情况下,Windows Presentation Foundation (WPF)会隐式调用Shutdown: 当ShutdownMode设置为OnLastWindowClose时。 当关机模式设置为OnMainWindowClose时。 当用户结束会话,而SessionEnding事件未被处理或在未取消的情况下被处理时。

请注意Application.Current.Shutdown();只能从创建Application对象的线程调用,即通常是主线程。