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

我试过:

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

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


当前回答

另一种方法是:

System.Diagnostics.Process.GetCurrentProcess().Kill();

这将强制终止应用程序。它总是有效的,即使在多线程应用程序中也是如此。

注意:注意不要在另一个线程中丢失未保存的数据。

其他回答

如果你想从另一个没有创建应用程序对象的线程中退出,请使用:

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

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

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

private void _MenuExit_Click(object sender, RoutedEventArgs e)
{
   System.Windows.Application.Current.MainWindow.Close();
}

//Override the onClose method in the Application Main window

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    MessageBoxResult result =   MessageBox.Show("Do you really want to close", "",
                                          MessageBoxButton.OKCancel);
    if (result == MessageBoxResult.Cancel)
    {
       e.Cancel = true;
    }
    base.OnClosing(e);
}

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

使用方法如下:

Environment.Exit(0)

Caliburn微调味

public class CloseAppResult : CancelResult
{
    public override void Execute(CoroutineExecutionContext context)
    {
        Application.Current.Shutdown();
        base.Execute(context);
    }
}

public class CancelResult : Result
{
    public override void Execute(CoroutineExecutionContext context)
    {
        OnCompleted(this, new ResultCompletionEventArgs { WasCancelled = true });
    }
}