Я использую следующее в своем приложении, оно немного запутанное, но работает.Следующий код находится в App.xaml.cs:
/// <summary>
/// Indicates whether the application needs to quit due to a previous exception
/// </summary>
private static bool _appMustQuit = false;
/// <summary>
/// Exception class that will be unhandled causing application to quit
/// </summary>
private class AppQuitException : Exception {}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException( object sender,
ApplicationUnhandledExceptionEventArgs e )
{
if( ( e.ExceptionObject is AppQuitException ) == false ) {
Debug.WriteLine( "App:Application_UnhandledException - " + e.ToString() );
if( Debugger.IsAttached ) {
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
// Compose error report
StringBuilder report = new StringBuilder( 1024 );
report.AppendFormat( "{0}", LangResources.ErrorReportContent );
report.AppendFormat( "Message: {0}\n", e.ExceptionObject.Message );
if( e.ExceptionObject.InnerException != null ) {
report.AppendFormat( "Inner: {0}\n", e.ExceptionObject.InnerException.Message );
}
report.AppendFormat( "\nStackTrace: {0}\n", e.ExceptionObject.StackTrace );
if( MessageBox.Show( "Unexpected Error", "Error", MessageBoxButton.OKCancel )
== MessageBoxResult.OK ) {
e.Handled = true;
// Email the error report
Tasks.ComposeEmail( "\"Developer\" <your@emailaddress.com>", "MyApp Error Report",
report.ToString() );
_appMustQuit = true;
}
}
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated( object sender, ActivatedEventArgs e )
{
var state = PhoneApplicationService.Current.State;
if( state.ContainsKey( "AppMustQuit" ) ) {
throw new AppQuitException();
} else {
// Restore other tombstoned variables
}
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated( object sender, DeactivatedEventArgs e )
{
if( _appMustQuit ) {
state["AppMustQuit"] = true;
} else {
// Save other variables for tombstoning
}
}
Tasks
- это статический класс с набором вспомогательных функций из пространства имен Microsoft.Phone.Tasks
.
using Microsoft.Phone.Tasks;
namespace MyApp
{
/// <summary>
/// Utility class for performing various phone tasks
/// </summary>
public static class Tasks
{
/// <summary>
/// Composes an email using the specified arguments
/// </summary>
/// <param name="to">The recepient(s) of the email</param>
/// <param name="subject">Email subject</param>
/// <param name="body">Email contents</param>
/// <param name="cc">The recipient(s) on the cc line of the email</param>
public static void ComposeEmail( string to, string subject, string body,
string cc = "" )
{
var task = new EmailComposeTask() {
To = to,
Subject = subject,
Body = body,
Cc = cc,
};
task.Show();
}
}
}
Toнемного объясните код, используя EmailComposeTask
, и ваше приложение будет захоронено.Поскольку я не хочу продолжать выполнение приложения после необработанного исключения, я сохраняю логическое значение в словаре PhoneApplicationService
State
, чтобы после отправки пользователем сообщения электронной почты при повторном пробуждении приложенияЯ могу искать это логическое значение и выдавать другое исключение, которое намеренно не обрабатывается.Это второе исключение приводит к закрытию приложения.