Will Dean
Will Dean

Reputation: 39500

Using winforms default exception handler with WPF apps

For simple 'internal use only' apps, Winforms has a useful default exception handler, which allows an 'ignore', and tells you what the exception was.

WPF apps don't seem to get this nice exception handling - you always have to exit the application.

Obviously I can write my own default exception handler for WPF, but is there a simple way to use the one which must already be in the framework for Winforms, but with WPF?

Upvotes: 2

Views: 788

Answers (2)

itowlson
itowlson

Reputation: 74802

I think there are two parts to this question: how to hook up your own exception handler so as to allow the app to continue, and whether it's possible to reuse the Windows Forms unhandled exception UI.

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 default unhandled exception processing -- i.e. the app will not automatically shut down. (Of course your event handler can still shut it down.) Handled is not set to true by default so you must do this explicitly.

For the second part, see System.Windows.Forms.ThreadExceptionDialog. This is officially "not intended for use from your code," and is not documented in any useful way, so it's not wise to rely on it for production applications. However if you are willing to take a chance then you can create an instance of this class and ShowDialog() it. In .NET 3.5, it returns DialogResult.Cancel to mean "ignore exception and continue" and DialogResult.Abort to mean "quit." These values are not documented and should be treated as implementation details though!

Upvotes: 3

Will Dean
Will Dean

Reputation: 39500

OK, I poked around in 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 need to play with the namespaces slightly on your application class, but other people might find it useful for simple utility apps.

Upvotes: 3

Related Questions