我的基于GUI桌面的WPF 4.0(C#.Net 4.0)程序适用于SQL Server数据库。每次运行我的应用程序时,它都会通过ADO.NET Entity Framework创建与SQL Server的连接,如果SQL Server无法访问,则会抛出异常并显示带有通知的MessageBox
。
现在我希望在用户阅读此消息后,应用程序将关闭。我找到了三种方法:
Process.GetCurrentProcess().Kill();
要么
this.Shutdown(); // Application.Current.Shutdown()
要么
System.Environment.Exit(0);
所有这些都可以正常工作并做我需要的 - 在Windows任务管理器中关闭应用程序并终止应用程序进程。
我想知道:
Application.Current.Shutdown()
和this.Shutdown()
以同样的方式关闭申请吗?或者可能还有另一种更合适的方法来关闭WPF GUI应用程序?
当我收到错误时,Application.Exit()
对我不起作用:
事件'
System.Windows.Application.Exit
'只能出现在+ =或 - =的左侧
谢谢。
使用Application.Current.Shutdown();
在App.xaml中添加ShutdownMode =“OnMainWindowClose”
private void ExitMenu_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
@DamianLeszczyński - Vash的答案几乎涵盖了你提出的4个具体问题。关于Application.Exit()
的最后一个问题,这是您可以订阅的事件,而不是您可以调用的方法。它应该像这样使用:
Application.Current.Exit += CurrentOnExit;
//this.Exit += CurrentOnExit; would also work if you're in your main application class
...
private void CurrentOnExit(object sender, ExitEventArgs exitEventArgs)
{
//do some final stuff here before the app shuts down
}