当用户从文件菜单中单击退出菜单项时,应该如何退出应用程序?
我试过:
this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();
还有很多其他的。没有什么工作。
当用户从文件菜单中单击退出菜单项时,应该如何退出应用程序?
我试过:
this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();
还有很多其他的。没有什么工作。
当前回答
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 });
}
}
其他回答
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()来退出应用程序,你可能会得到一个System. current . shutdown()。调用线程不能访问该对象,因为它属于另一个线程。如果从不同的线程调用它。要解决这个问题,您可以像这样包装调用
Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());
总结一下,有几种方法可以做到这一点。
1)终止进程,跳过结束、错误处理等:
Process.GetCurrentProcess().Kill();
2)关闭当前应用程序,这可能是正确的方式,因为它调用退出事件:
Application.Current.Shutdown();
or
this.Shutdown();
(当在app类的实例中调用时)
3)关闭当前app(所有表单必须提前关闭/完成):
this.Close();
(当在app类的实例中调用时)
4)退出环境,终止应用程序:
Environment.Exit(0);
此外,你可能想在这里阅读退出状态
我是这样做的:
// 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.
这是我个人的经验。最后,使用最适合您的场景的方法。这只是另一条信息。
这应该可以达到目的:
Application.Current.Shutdown();
如果你感兴趣,这里有一些我认为有用的额外材料:
申请详情。当前的
WPF应用程序生命周期