Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
看到题目可能有些同学觉得这是一个老生常谈的问题了,确实这是一个 known issue 但我发现还是有同学在询问这个问题,所以在这里给大家总结分享一下。
首先第一个问题 MessageBox显示出来以后,如果用户不理会 Message 页面,大概等上10秒钟程序就会自动退出。(这个现象在Debug时不会出现)
先简单分析一下这个问题的原因,首先为什么在Debug的时候应用不会出问题,很简单我们在调试应用的时候很有可能一个断点停留10秒钟以上(一个返回值阻塞主线程),然而应用在非Debug的情况下出现这种现象,SDK会认为你的代码有问题会强制退出。
其实解决这个问题的方法很简单,既然知道这个问题的原因了,使用一个异步方法(线程)来实解决这个问题。
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { e.Cancel = true; base.OnBackKeyPress(e); this.Dispatcher.BeginInvoke(delegate { if (MessageBox.Show("是否要退出程序?", "退出", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { } }); }
当然肯定有同学会问 在调用MessageBox之前先把 e.Cancel 设置成 True 了那怎么退出应用呢? 这也算是一个老问题了(WP7时代遗留问题),这里我也是总结一下经验,从网上看到的一些方法。
Windows Phone 8 更新 此方法可以直接终结应用。
Application.Current.Terminate();
但是此方法这里不会调用页面的 OnNavigatedFrom 事件 和App中的Application_Closing 事件,所以在调用此方法前要注意保存用户数据。
Windows Phone 7
首先 XNA中的Game.Exit() 不建议使用因为在应用商店审核的时候会遇到问题,导致不能上商店。
目前唯一的靠谱方法就是通过抛异常并且在App文件中的Application_UnhandledException事件中处理它:
网络上抛出异常的方式有两种
1. 自定义的异常
private class QuitException : Exception { } public static void Quit() { throw new QuitException(); } // Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (e.ExceptionObject is QuitException) return; if (System.Diagnostics.Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break(); } }
最后使用App.Quit()退出应用。
2. 利用 NavigationService.GoBack();退出应用
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { e.Cancel = true; base.OnBackKeyPress(e); this.Dispatcher.BeginInvoke(delegate { if (MessageBox.Show("是否要退出程序?", "退出", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { while (NavigationService.BackStack.Any()) { NavigationService.RemoveBackEntry(); } NavigationService.GoBack(); } }); }
同理,在 Application_UnhandledException 中处理一下这个异常。