Search code examples
wpfunhandled-exception

Application Unhandled Exception with WPF Dialog Not Functioning


I have an application where I have a handler for unhandled exceptions to show the user a nicer dialog and allow them to submit a report of the failure.

I originally had a Winforms dialog that came up and it was working ok. However I decided to update it to a WPF dialog to match everything else in the apps that has been upgraded to WPF and it is showing some strange behavior.

I originally had

AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf Boom

and in the handler (msg is a constructed string message):

    Dim d As New Dlg_Boom(msg)
    d.ShowDialog()

    Me.Shutdown()

When I switched to the WPF dialog, the dialog comes up, but then I immediately get the 'Program has stopped working' windows dialog.

I have also tried using both:

    AddHandler Dispatcher.UnhandledException, AddressOf Boom
    AddHandler Application.DispatcherUnhandledException, AddressOf Boom

With these I get the option to set e.Handled=True. If I leave it false, I get the not working dialog, if I set it to true it flashes my WPF dialog and immediately closes it.

It's like it's ignoring the fact that it's ShowDialog() and treating it like Show() and not waiting for it to return. Oddly if I put a messagebox right before the ShowDialog() call it works as expected and waits for it to return.

I'm very puzzled, anyone have any insight on this?


Solution

  • Ok I'm not sure this is really a solution so I'm not marking it as the answer but it seems that it just doesn't like WPF dialogs in the unhandled exception handlers. I tried just showing a blank WPF dialog to make sure it wasn't somethign strange in my code and it does the same thing. As soon as I put a Winforms dialog in it stops properly in the ShowDialog routine and waits for it to return. When I call that with WPF it shows the dialog but keeps executing code (my next command is shutdown) so it just flashes the dialog and then goes away. I also tried just putting a message box right after the ShowDialog() call and it puts up the dialog and immediately shows the message box. As soon as I dismiss the message box it closes the application.

    Anyway what I ended up doing is creating a WinForms dialog that just holds an ElementHost object and turning my WPF dialog into a WPF UserControl. Then I hosted the WPF control inside the ElementHost. It seems kind of backwards and ugly but it works...

    If anyone has a better suggestion to use pure WPF I will mark it as the answer.