internal static void OnUnhandledException(object sender, Exception ex) { try { Application app = Application.Current; string unmanaged_report = ex.ToString(); if (app != null && app.UnhandledException != null) { ApplicationUnhandledExceptionEventArgs args = new ApplicationUnhandledExceptionEventArgs(ex, false); try { app.UnhandledException(sender, args); if (args.Handled) { unmanaged_report = null; } } catch (Exception ex2) { Console.WriteLine("Exception caught in Application UnhandledException handler: " + ex2); unmanaged_report = ex2.Message; } } else { Console.WriteLine("Unhandled Exception: " + ex); } if (unmanaged_report != null) { Deployment.Current.EmitError(4004, unmanaged_report); } } catch { // Make this completely safe. } }