Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't wait for result of messageBox

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?

like image 860
Ingó Vals Avatar asked Dec 26 '22 19:12

Ingó Vals


2 Answers

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.

like image 121
Renier Avatar answered Dec 29 '22 12:12

Renier


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 several Show overloads. For more information about owner windows, see Window.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.

like image 41
Alexey Ivanov Avatar answered Dec 29 '22 10:12

Alexey Ivanov