当用户从文件菜单中单击退出菜单项时,应该如何退出应用程序?
我试过:
this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();
还有很多其他的。没有什么工作。
当用户从文件菜单中单击退出菜单项时,应该如何退出应用程序?
我试过:
this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();
还有很多其他的。没有什么工作。
当前回答
Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
其他回答
根据需要使用以下任何一种方法:
1.
App.Current.Shutdown();
OR
Application.Current.Shutdown();
2.
App.Current.MainWindow.Close();
OR
Application.Current.MainWindow.Close();
以上所有的方法都会调用Window类的关闭事件,并且执行可能会在某个时候停止(因为通常应用程序会设置像'are you sure?或“关闭前要保存数据吗?”,在窗口完全关闭之前)
3.但如果您想立即终止应用程序而不发出任何警告。使用下面的
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.
这是我个人的经验。最后,使用最适合您的场景的方法。这只是另一条信息。
在xaml代码中,你可以调用一个预定义的SystemCommand:
Command="SystemCommands.MinimizeWindowCommand"
我认为这应该是首选的方式……
Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
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 });
}
}