当用户从文件菜单中单击退出菜单项时,应该如何退出应用程序?
我试过:
this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();
还有很多其他的。没有什么工作。
当用户从文件菜单中单击退出菜单项时,应该如何退出应用程序?
我试过:
this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();
还有很多其他的。没有什么工作。
当前回答
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)
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);
}
这应该可以达到目的:
Application.Current.Shutdown();
如果你感兴趣,这里有一些我认为有用的额外材料:
申请详情。当前的
WPF应用程序生命周期
如果你想从另一个没有创建应用程序对象的线程中退出,请使用:
另一种方法是:
System.Diagnostics.Process.GetCurrentProcess().Kill();
这将强制终止应用程序。它总是有效的,即使在多线程应用程序中也是如此。
注意:注意不要在另一个线程中丢失未保存的数据。