MessageBox
A MessageBox is a dialog the operating system draws: a text, an icon, one to three buttons and a return value. It is the fastest way to ask a question or report a failure, and the most overused control in a desktop application. This lesson is as much about when not to use it as about how.
One call, one answer
using System;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
internal sealed class Form1 : Form
{
private readonly RichTextBox _notes = new() { Dock = DockStyle.Fill };
private bool _dirty;
public Form1()
{
Text = "Unsaved notes";
ClientSize = new Size(420, 260);
_notes.TextChanged += (sender, e) => _dirty = true;
var save = new Button { Text = "&Save", Dock = DockStyle.Top };
save.Click += (sender, e) =>
{
_dirty = false;
Text = "Saved";
};
var close = new Button { Text = "&Close", Dock = DockStyle.Bottom };
close.Click += (sender, e) => Close();
FormClosing += AskToSave;
Controls.Add(_notes);
Controls.Add(save);
Controls.Add(close);
}
private void AskToSave(object? sender, FormClosingEventArgs e)
{
if (!_dirty)
{
return;
}
var answer = MessageBox.Show(
this,
"Save the changes before closing?",
"Unsaved notes",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1);
if (answer == DialogResult.Cancel)
{
e.Cancel = true;
}
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The overload with six arguments is the one a form uses: the owner, the text, the caption, the buttons, the icon and which button has the focus. The return value is a DialogResult, which is the same type a modal form returns, so a dialog of your own can replace this call without changing the code around it.
Buttons, icons and the default
- MessageBoxButtons.OK is the default: one button, and the call always returns OK.
- MessageBoxButtons.OKCancel, YesNo, YesNoCancel, RetryCancel and AbortRetryIgnore: the sets the platform draws. The return value is always one of the buttons of the set: YesNo never returns Cancel.
- MessageBoxIcon.Information, Warning, Error, Question: the picture. An icon is not decoration: it is what tells the user whether this is news, a question or a failure, before the text is read.
- MessageBoxDefaultButton.Button1 or Button2: which button has the focus and answers Enter. The default for a destructive question is the safe answer, not the destructive one.
- MessageBoxOptions.RightAlign and RtlReading: text alignment for a right-to-left culture.
The text is plain: newlines work, and nothing else does. A message that needs a bold word, a link or a list is a form of your own with the same ShowDialog contract, which is the next lesson but one.
The owner
The overload with an IWin32Window owner does two things a call without one does not: the box is centred on its owner, and the owner cannot be activated while the box is open. this in a form is the owner, and a message box raised from a background thread without one can appear behind the window it is about.
There is a rule about message boxes that a code review enforces sooner or later: a box inside a loop or inside a handler that can run many times is a box the user cannot escape. A MessageBox in Validating is the classic mistake, because the event fires again as soon as the box closes. The error belongs on the field with an ErrorProvider.
A decision that runs
What the answer means is application logic, and it is a function of the answer and the state. This program prints the decision for four cases, and it runs here:
using System;
foreach (var answer in new[] { ("Yes", true), ("No", true), ("Cancel", true), ("Yes", false) })
{
Console.WriteLine($"{answer.Item1,-6} dirty={answer.Item2,-5} -> {Decide(answer.Item1, answer.Item2)}");
}
Console.WriteLine($"answers: 4");
static string Decide(string answer, bool dirty) => answer switch
{
"Yes" => dirty ? "save, then close" : "close",
"No" => "close without saving",
_ => "stay open",
};
dotnet run
Yes dirty=True -> save, then close
No dirty=True -> close without saving
Cancel dirty=True -> stay open
Yes dirty=False -> close
answers: 4
The output is the real run. The last line is the one a form forgets: a Yes with nothing to save is a close, not a save, because a Save that writes an empty document over the previous file is worse than no prompt at all. The Cancel and the default case both keep the form open, which is the safe answer for any result the code does not recognise. In the form, this function is what AskToSave calls after MessageBox.Show returns, and the logic that decides is testable without a dialog.
Exercises
- Add a case for RetryCancel and print its decision, and run the program.
- Change the switch so that a No with unsaved changes asks again, and explain the loop you would need.
- Explain from the documentation why a MessageBox in a Validating handler fires more than once.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which overload does a form use to own its message box?
Answer
The one with an IWin32Window owner as its first argument
The owner centres the box and keeps the form inactive while it is open.
-
What does MessageBox.Show return?
Answer
A DialogResult, one of the buttons of the set
It is the same type a modal form returns.
-
Which buttons does MessageBoxButtons.YesNo show?
Answer
Yes and No, and the call returns one of them
The return value is always one of the buttons of the set.
-
What does MessageBoxDefaultButton decide?
Answer
Which button has the focus and answers Enter
For a destructive question the safe answer is the default.
-
What does an icon tell the user?
Answer
Whether this is news, a question or a failure
It is read before the text is.
-
Why is a MessageBox inside Validating a mistake?
Answer
The event fires again as soon as the box closes, so the box reappears
The error belongs on the field with an ErrorProvider.
-
What happens to the owner form while a message box is open?
Answer
It cannot be activated
The box is modal to its owner.
-
What did the run print for Yes with dirty=False?
Answer
close
There is nothing to save, so the answer is a plain close.
-
Which result keeps the form open in the save-changes decision?
Answer
Cancel, and any result the code does not recognise
The default branch of the switch is the safe answer.
-
When is a message box the wrong tool for an error?
Answer
When the error belongs to one field the user is editing
A field error is shown next to the field; a box interrupts the work.
Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.
Article author: Arthur Isaev