When catching a unhandled exception in a client application currently in user testing I made a code like this.
catch(Exception ex)
{
var result = MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
Current.Shutdown();
}
But the message box only appears very quickly and then the program shuts down. WHy doesn't the code wait for result to be apparent. How would I do that?
I had a similar issue. Problem is that exception is thrown before the main window is displayed and thus there is no Window to display the message box on. Swamy's answer mere forced a time delay so that the window can be initialized. IMO not too elegant. Found a better solution [here]WPF MessageBox not waiting for result [WPF NotifyIcon].
Just specify the MessageBoxOptions.DefaultDesktopOnly
in the MessageBox.Show(....) method
.
From the documentation to MessageBox
class:
Message boxes always have an owner window. By default, the owner of a message box is the window that is currently active in an application at the time that a message box is opened. However, you can specify another owner for the
Window
by using one of severalShow
overloads. For more information about owner windows, seeWindow.Owner
.
Thus your problem is really similar to this question where the application exists before message box is dismissed by the user.
The first thing to try is to pass null
as Window
parameter.
MessageBox.Show(null, ex.Message, "Error", MessageBoxButton.OK);
If you have an instance of Window
class, for example your main window object, pass it instead of null
:
MessageBox.Show(mainWindow, ex.Message, "Error", MessageBoxButton.OK);
If you are currently in any of the main window methods, you can pass this
as the Window:
MessageBox.Show(this, ex.Message, "Error", MessageBoxButton.OK);
Use null
only in case where there's no main window object available at this time.
Look at MessageBox sample. You should be able to see the difference between the cases where this
is passed as the owner window and where null
is passed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With