WPF MessageBox

Jose Leon

A message box is a small dialog window display on the screen for the users. It can have an icon, a message and a button (or a set of buttons) for the user to provide feedback. The MessageBox is contained within the System.Windows.Forms namespace and is part of the Windows Forms library and objects since the launch of the .NET Framework. This class contains a static method called Show that draws the dialog in the screen. It also returns an enumeration with the values No, Yes, Cancel, OK and None.

MessageBox Example

Below you can find the code on how to show a simple message box with an OK button. After pressing the OK button, the dialog will close:



DialogResult result = System.Windows.Forms. MessageBox.Show("Hello World" );

The result variable will contain which button the user selected. In this case, result will always be OK.

MessageBox with Title

In this example, we’re creating a message box with a message an OK button but we’re also setting a caption that shows on the top bar:



DialogResult result = System.Windows.Forms. MessageBox.Show("Hello World" ,"My App" );

MessageBox Yes/No

When we need to gather feedback from the user about a question, we can create a message box with a message and two buttons, one for YES and one for NO using the code below:



DialogResult result = System.Windows.Forms. MessageBox.Show("Hello World" ,"My App",MessageBoxButtons.YesNo);

Handling the MessageBox result

After we’ve capture the results, we need to take an action about it. This is as simple as testing the value in the result variable as shown below:










DialogResult result = System.Windows.Forms.MessageBox .Show("Hello World" ,"My App",MessageBoxButtons.YesNo);

if (result == System.Windows.Forms. DialogResult.Yes)






MessageBox style

As you may have already noticed, the MessageBox class uses the User32 libraries directly preventing it to provide a true WPF experience. In this case, if you still want to produce this kind of experience you’ll need to create your own windows screen or use a third party library. In our tests, we recommend you use the WPF Toolkit on CodePlex that already has a Message Box that you can style as needed.

MessageBox Icon

You can also set an icon to show on the left part on the message box. This is used to give direct information to the user about what’s been said in the box. For example, if it’s a question, information or an error has occurred. For this, there’s an enumeration that has all the possible values as follows: None Hand Question Exclamation Asterisk Stop Error Warning Information Below is the code of message box with an error icon:



DialogResult result = System.Windows.Forms. MessageBox.Show("Hello World" ,"My App",MessageBoxButtons.YesNo, MessageBoxIcon.Error);


All posts

  • licensing
  • analytics

Easy .NET Protection

Purchase template