#196 – Getting a Result Back from a MessageBox

The MessageBox.Show method always returns a result, indicating which button a user clicked to dismiss the dialog box.  If you choose, you can check the result to see which button the user clicked.  The value returned will always be a member of the MessageBoxResult enumeration.

            // Not checking result
            MessageBox.Show("Hi!");

            // Always resturns MessageBoxResult.OK, since the dialog only has one button
            MessageBoxResult res = MessageBox.Show("Hello again");

In the above examples, the result didn’t really matter.  But you often want to know which of two or more buttons the user clicked.

            MessageBoxResult res = MessageBox.Show("Do you like brussel sprouts?", "Green Food", MessageBoxButton.YesNo);

            if (res == MessageBoxResult.No)
                MessageBox.Show("Me neither");
            else
                MessageBox.Show("Wow, you're a cruciferous vegetable lover!");

#195 – The Venerable MessageBox

The MessageBox class, in the System.Windows namespace, provides an easy way to display modal dialog boxes.

MessageBox provides a series of overloads of its static Show method, which you call to display a dialog box.

Here are some of the more common overloads:

Text message and a caption

            MessageBox.Show("Truffles are easy to make!", "Chocolate Alert");

.

Specify button(s) that appear on dialog

            MessageBox.Show("Do you like Belgian chocolate?", "Belgians", MessageBoxButton.YesNo);

.

Include buttons and icon

            MessageBox.Show("About to eat last truffle.  Proceed?", "Almost Out", MessageBoxButton.OKCancel, MessageBoxImage.Exclamation);

.

Buttons, icon and default result

The default result is the MessageBoxResult value that is returned if the user presses Return.

            MessageBoxResult result =
                MessageBox.Show("Have you been to Bruges?", "Lovely Spot", MessageBoxButton.YesNo, MessageBoxImage.Information, MessageBoxResult.No);

.

Options

            MessageBox.Show("In Bruges, I recommend the truffles, the belfry tower and a lovely canal trip.", "Tip", MessageBoxButton.OK,
                MessageBoxImage.Stop, MessageBoxResult.OK, MessageBoxOptions.RightAlign);