Using winforms default exception handler with WPF applications

For simple "internal-only" applications, Winforms has a useful default exception handler that lets you "ignore" and tells you what the exception is.

WPF apps don't seem to be able to handle this great exception handling - you always have to exit the app.

Obviously, I can write my own default exception handler for WPF, but is there an easy way to use the one that should already be within Winforms but with WPF?

+2


source to share


2 answers


I think there are two parts to this question: how to hook up your own exception handler to continue the application, and whether the Windows Forms unhandled exception UI can be reused.

For the first part, see Application.DispatcherUnhandledException. If you subscribe to this event and your event handler sets DispatcherUnhandledExceptionEventArgs.Handled to true, then WPF will skip unhandled exception handling by default - that is, the application will not be automatically shut down. (Of course, your event handler can still disable it.) By default, handled by default is not set to true, so you must do this explicitly.



For the second part, see System.Windows.Forms.ThreadExceptionDialog. This is officially "not intended to be used from your code" and is not documented in any useful way, so it is impractical to rely on it for production applications. However, if you want to take advantage of the opportunity, you can instantiate this class and ShowDialog (). In .NET 3.5 it returns DialogResult.Cancel to mean "ignore exception and continue" and DialogResult.Abort means "exit". These values ​​are not documented and should be considered implementation details though!

+3


source


Ok, I poked into the Winforms source and it turns out that the standard Winforms exception dialog is public. So you need to use a WPF style DispatcherUnhandledException handler and do something like this:

void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    using (ThreadExceptionDialog dlg = new ThreadExceptionDialog(e.Exception))
    {
        DialogResult result = dlg.ShowDialog();
        if (result == DialogResult.Abort)
        {
            Environment.Exit(-1);
        }
        else if (result == DialogResult.Cancel)
        {
            e.Handled = true;
        }
    }
}

      



You need to add a reference to System.Windows.Forms and may have to fiddle with the namespaces in the Application class a bit, but other people may find this useful for simple applications.

+3


source







All Articles