The System.Windows.Forms.MessageBox is a static category that’s wont to show message boxes for prompting, confirmation and warning users. To show a message box, simply call the Show method of the MessageBox class. The simplest version of the Show method is the one that accepts a string message as an argument.

MessageBox.Show("Hello World!"); 

You can also specify the title of the message box by using another overloaded version of the Show method.

MessageBox.Show("Hello World!", "A Message"); 

You can also change the buttons that will be shown in the message box if you don’t want to use the default OK button. You can do this by using the System.Windows.Forms.MessageBoxButtons enumeration.

MessageBox.Show("Hello World!", "A Message", MessageBoxButtons.OKCancel); 

The table below shows the members of the MessageBoxButtons enumeration.

Member Buttons Shown
AbortRetryIgnore Abort, Retry, Ignore
OK OK
OKCancel OK, Cancel
RetryCancel Retry, Cancel
YesNo Yes, No
YesNoCancel Yes, No, Cancel

The Show() method returns a value from the System.Windows.Forms.DialogResult enumeration. This is useful to determine what button you pressed in the message box. For example, if you click the “Yes” button in the message box, then the Show() method will return the value DialogResult.Yes.

DialogResult result;
result = MessageBox.Show("What is your choice?");

if (result == DialogResult.Yes)
{
   //You pressed the Yes button
}
if (result == DialogResult.No)
{
   //You pressed the No button
}

Please note that the Form class also has a DialogResult property. This is not the System.Windows.Forms.DialogResult.

You can also add an icon for your message box to further imply the purpose of the message. You do this by using the members of the MessageBoxIcon enumeration.

MessageBox.Show("Hello World!", "A Message", 
 MessageBoxButtons.OK, MessageBoxIcon.Information); 

The table below shows the different icons that you can use for your message box.

Icon Member Usage
Asterisk
Information
Used when showing information to the user.
Error
Hand
Stop
Used when showing error messages.
Exclamation
Warning
Used when showing warning messages.
Question Used when asking a question to the user.

You can use the MessageBoxIcon.None to indicate that the message box will have no icon.

The MessageBoxDefaultButton enumeration tells which of the button is the default, that is, the one that is pressed when the enter key in the keyboard is pushed. It has only 4 members which are Button1Button2Button3Button4. For example, in a message box that has an OK and a Cancel buttons, using MessageBoxDefaultButton.Button1 will make the OK button as the default. When the message box is shown and you pressed Enter in the keyboard, the OK button is pressed.

MessageBox.Show("Hello World!", "A Message",
 MessageBoxButtons.OKCancel, MessageBoxDefaultButton.Button1);