A custom modal dialog
A MessageBox asks one of three questions. Everything else a form needs to ask needs a dialog of its own: a name, a folder, a date range, a set of options. In WinForms that dialog is a Form shown with ShowDialog, and the difference between it and the main window is six properties and a result.
A form that returns a value
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 Label _name = new() { Location = new Point(16, 16), AutoSize = true, Text = "notes.txt" };
public Form1()
{
Text = "The main window";
ClientSize = new Size(360, 120);
var rename = new Button { Text = "&Rename...", Location = new Point(16, 56) };
rename.Click += (sender, e) =>
{
using var dialog = new RenameDialog(_name.Text);
if (dialog.ShowDialog(this) != DialogResult.OK)
{
return;
}
_name.Text = dialog.NewName;
};
Controls.Add(_name);
Controls.Add(rename);
}
}
internal sealed class RenameDialog : Form
{
private readonly TextBox _name;
public RenameDialog(string current)
{
Text = "Rename";
FormBorderStyle = FormBorderStyle.FixedDialog;
StartPosition = FormStartPosition.CenterParent;
MinimizeBox = false;
MaximizeBox = false;
ShowInTaskbar = false;
ClientSize = new Size(320, 110);
_name = new TextBox { Location = new Point(16, 20), Width = 280, Text = current };
var ok = new Button { Text = "OK", DialogResult = DialogResult.OK, Location = new Point(130, 60) };
var cancel = new Button { Text = "Cancel", DialogResult = DialogResult.Cancel, Location = new Point(218, 60) };
AcceptButton = ok;
CancelButton = cancel;
NewName = current;
Controls.Add(_name);
Controls.Add(ok);
Controls.Add(cancel);
}
public string NewName { get; private set; }
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The main window owns the dialog in a using statement, which disposes it after the result is read; ShowDialog(this) makes it modal to that window; and the button with DialogResult.OK closes the dialog and makes ShowDialog return OK. NewName is a plain property that the caller reads after the result: the dialog returns a DialogResult and the value is beside it, which is the shape every dialog in WinForms has.
The parts of a dialog
- FormBorderStyle.FixedDialog and MinimizeBox = false, MaximizeBox = false: a dialog does not resize or minimise.
- ShowInTaskbar = false: a modal dialog is not a window of its own in the task bar.
- StartPosition.CenterParent: centred on the form that opened it. It needs the owner that ShowDialog(owner) passes.
- AcceptButton and CancelButton: Enter presses the first and Escape the second, and the second also answers the window's close button.
- DialogResult on a button: the value the dialog returns when that button is pressed. The default of a button is None, which does not close the dialog.
- DialogResult = DialogResult.None inside a FormClosing handler: refuses the close. That is how a dialog whose OK button must validate keeps itself open.
A button with DialogResult.OK closes the form without raising Click in a handler that could cancel it. A dialog that has to check its values before it closes sets the button's DialogResult to None and closes by hand:
using System;
using System.Windows.Forms;
internal sealed class RenameDialog : Form
{
private readonly TextBox _name = new() { Width = 240 };
public RenameDialog(string current)
{
_name.Text = current;
var ok = new Button { Text = "OK", DialogResult = DialogResult.None };
ok.Click += (sender, e) =>
{
if (_name.Text.Trim().Length == 0)
{
MessageBox.Show(this, "A name is required", "Rename");
return;
}
DialogResult = DialogResult.OK;
Close();
};
AcceptButton = ok;
Controls.Add(_name);
Controls.Add(ok);
}
}
That block is a fragment: a class with no Main, so the checker counts it and does not build it. Setting DialogResult on the form and then calling Close() is the manual version of what the property on the button does, and it is what a dialog with a rule needs: the click runs, the rule decides, and only then does the dialog close.
The value it returns
A dialog has three ways to hand a value back, and the choice is about how much it returns:
- A property on the dialog, read after ShowDialog returned OK. The NewName above, and the shape of almost every dialog.
- The Tag of the dialog: a single object, which avoids a property for a one-off.
- A constructor that takes a callback, for a dialog that reports while it is open rather than at the end. Rare in a desktop application, and usually a sign that the dialog is doing too much.
A dialog that is shown with Show instead of ShowDialog is a window, not a dialog: it returns immediately, the owner stays usable, and there is no result. A modeless window is right for a palette and wrong for a question.
The rules that run
The rule that decides whether the OK button may close the dialog is the same kind of method as the validator of lesson 034, and it runs here:
using System;
foreach (var input in new[] { "notes.txt", "", " ", "a/b" })
{
var dialog = new RenameDialog(input);
var state = dialog.CanAccept ? "ok" : $"blocked: {dialog.Message}";
Console.WriteLine($"[{input}] name='{dialog.Name}' {state}");
}
Console.WriteLine("cancel returns DialogResult.Cancel and the old name");
internal sealed class RenameDialog
{
public RenameDialog(string current)
{
Name = current.Trim();
Check();
}
public string Name { get; set; }
public string? Message { get; private set; }
public bool CanAccept => Message is null && Name.Length > 0;
public void Check()
{
if (Name.Length == 0)
{
Message = "A name is required";
return;
}
if (Name.IndexOfAny(new[] { '/', '\\' }) >= 0)
{
Message = "A name cannot contain a slash";
return;
}
Message = null;
}
}
dotnet run
[notes.txt] name='notes.txt' ok
[] name='' blocked: A name is required
[ ] name='' blocked: A name is required
[a/b] name='a/b' blocked: A name cannot contain a slash
cancel returns DialogResult.Cancel and the old name
The output is the real run. The empty and the two-space inputs reach the same message, because the constructor trims before it checks; the slash is refused because a file name is not a path. CanAccept is the state the OK button's Enabled follows, and the last line names the other half of the contract: a dialog that returns Cancel must leave the value it was given unchanged, which is why NewName starts as the current name and only the OK path replaces it.
Exercises
- Add a rule that refuses a name longer than twelve characters, and run the program with one.
- Make Check keep the first message instead of the last, and say which rule wins for an empty name with a slash.
- Explain from the documentation why a button with DialogResult.OK does not need a Click handler.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which call shows a form as a modal dialog?
Answer
ShowDialog(owner)
Show returns at once and leaves the owner usable.
-
What does a button whose DialogResult is OK do?
Answer
Closes the dialog and makes ShowDialog return OK
A button with DialogResult None does not close the dialog.
-
Which property centres a dialog on its owner?
Answer
StartPosition = FormStartPosition.CenterParent
It needs the owner that ShowDialog passes.
-
Which property keeps a dialog out of the task bar?
Answer
ShowInTaskbar = false
A modal dialog is not a window of its own in the task bar.
-
How does a dialog refuse to close in a FormClosing handler?
Answer
e.Cancel = true
Setting DialogResult.None on the button is the other half of a validating OK.
-
Where does a dialog put the value it returns?
Answer
In a property the caller reads after the result
DialogResult says whether; the property says what.
-
What does a dialog that returns Cancel owe the caller?
Answer
Its value is unchanged
The last line of the run names that half of the contract.
-
What did the run print for the two-space input?
Answer
name='' blocked: A name is required
The constructor trims before the rule runs.
-
Why is a dialog disposed with using?
Answer
It holds window handles that are released on dispose
The using statement disposes it after the result is read.
-
When is a modeless window the right choice?
Answer
For a palette that stays open while the user works
A question needs a modal dialog and a result.
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