当用户从文件菜单中单击退出菜单项时,应该如何退出应用程序?
我试过:
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 });
}
}
其他回答
如果你使用application . current . shutdown()来退出应用程序,你可能会得到一个System. current . shutdown()。调用线程不能访问该对象,因为它属于另一个线程。如果从不同的线程调用它。要解决这个问题,您可以像这样包装调用
Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());
根据需要使用以下任何一种方法:
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);
另一种方法是:
System.Diagnostics.Process.GetCurrentProcess().Kill();
这将强制终止应用程序。它总是有效的,即使在多线程应用程序中也是如此。
注意:注意不要在另一个线程中丢失未保存的数据。
如果你真的需要它来关闭,你也可以使用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 });
}
}