Several forms, MDI and settings
An application outgrows one form quickly: a settings window, an about box, a palette that stays open while the user works, an editor with a document per window. WinForms has three ways to open a second form, and one of them is called MDI, which is the multi-document interface of the 1990s. The lesson ends with settings, because an application that remembers its window size and its last folder is the same three questions about forms in a different dress.
Show and ShowDialog
- Show(): makes the form visible and returns at once. The caller continues, the form is independent, and the user can use both windows. This is the call for a palette, a tool window or a second document window.
- ShowDialog(owner): runs the form modally until it closes and returns its DialogResult. The caller waits, the owner cannot be used, and the form is a dialog. Lesson 042 builds one.
- Application.Run(form): starts the message loop with that form. It is not a way to open a second window; it is the beginning of the application.
Owner
Owner is the property that ties two windows together, and it has three effects a user notices:
- The owned form stays above its owner, so a palette is never lost behind the window it belongs to.
- The owned form minimises and restores with its owner, and it closes when the owner closes.
- The owned form does not appear as a separate window in the task bar.
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 Palette? _palette;
public Form1()
{
Text = "The editor";
ClientSize = new Size(480, 300);
var palette = new Button { Text = "&Palette", Location = new Point(16, 16) };
palette.Click += (sender, e) =>
{
if (_palette is { Visible: true })
{
_palette.Activate();
return;
}
_palette = new Palette { Owner = this };
_palette.FormClosed += (s, args) => _palette = null;
_palette.Show();
};
Controls.Add(palette);
}
}
internal sealed class Palette : Form
{
public Palette()
{
Text = "Palette";
ClientSize = new Size(200, 120);
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
Location = new Point(560, 80);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The field holds the palette so that a second click activates it instead of opening a second one, which is the bug a palette without the guard always has. ShowInTaskbar = false and a Manual position are what make it a palette; with an owner it also stays above the editor without a TopMost, which is the wrong tool because it would keep the palette above every application.
MDI
MDI puts several child windows inside one parent window, each with its own document, and one menu for all of them. It was the normal shape of a Windows application for a decade and is now a niche, but the properties are small:
using System;
using System.Drawing;
using System.Windows.Forms;
internal sealed class EditorForm : Form
{
public EditorForm(string title)
{
Text = title;
var inner = new RichTextBox { Dock = DockStyle.Fill };
Controls.Add(inner);
}
}
internal sealed class MainForm : Form
{
private readonly MenuStrip _menu = new();
public MainForm()
{
IsMdiContainer = true;
Text = "An MDI editor";
ClientSize = new Size(700, 460);
var window = new ToolStripMenuItem("&Window");
_menu.MdiWindowListItem = window;
_menu.Items.Add(window);
MainMenuStrip = _menu;
Controls.Add(_menu);
}
public void OpenDocument(string title)
{
var child = new EditorForm(title) { MdiParent = this };
child.Show();
}
}
That block is a fragment: a class with no Main, so the checker counts it and does not build it. Four properties carry MDI: IsMdiContainer on the parent, MdiParent on each child, ActiveMdiChild to read which one has the focus, and LayoutMdi with MdiLayout.Cascade or TileHorizontal to arrange them. MdiWindowListItem makes the named menu item list the open documents, which is the feature that made MDI useful.
A new application usually chooses a tab per document (lesson 028) or a window per document with Show and an Owner. MDI survives in applications written before 2010 and in ports of them.
Settings
A WinForms project in Visual Studio has a Properties.Settings class: a designer page that generates a strongly typed class with a property per setting, two scopes (Application is read-only and shared, User is per user and writable) and a Settings.settings file that becomes app.config. The class is generated, so it does not exist in a project written by hand, and the file it writes lives in the user's profile under %LOCALAPPDATA%. Settings.Default.Save() writes the user scope; Settings.Default.Reload() reads it again.
The platform-neutral answer, and the one this course uses, is a settings class of your own with System.Text.Json and a JSON file: one file, one class, defaults in the property initialisers, and a try around the read because a settings file is user-editable and will eventually be corrupt.
A settings file that runs
This program writes a settings object as indented JSON, reads it back and prints both the file and the loaded object, and it runs here:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
var path = Path.Combine(Path.GetTempPath(), "winforms-settings.json");
var settings = new AppSettings
{
Folder = "C:/notes",
FontSize = 11,
ShowStatusBar = false,
Recent = { "a.txt", "b.txt" },
};
File.WriteAllText(path, JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine(File.ReadAllText(path));
var loaded = JsonSerializer.Deserialize<AppSettings>(File.ReadAllText(path))!;
Console.WriteLine($"loaded: {loaded.Folder}, {loaded.FontSize} pt, status bar {loaded.ShowStatusBar}, {loaded.Recent.Count} recent");
Console.WriteLine($"defaults: {new AppSettings().FontSize} pt, {new AppSettings().Recent.Count} recent");
internal sealed class AppSettings
{
public string Folder { get; set; } = string.Empty;
public float FontSize { get; set; } = 9;
public bool ShowStatusBar { get; set; } = true;
public List<string> Recent { get; set; } = new();
}
dotnet run
{
"Folder": "C:/notes",
"FontSize": 11,
"ShowStatusBar": false,
"Recent": [
"a.txt",
"b.txt"
]
}
loaded: C:/notes, 11 pt, status bar False, 2 recent
defaults: 9 pt, 0 recent
The output is the real run. The file is readable and mergeable, which is the point of writing JSON rather than a binary blob: a support engineer can open it and a user can edit it. The defaults live in the property initialisers, so a file that lacks a property still yields the value the application expects, and the last line prints them from a fresh object rather than from the file. In a form the class is a field, loaded in the constructor and written in FormClosing, after the part of the close that the user cannot cancel.
Exercises
- Add a Recent list of three names and run the program again. Which lines change?
- Make FontSize a string and run it, then explain the exception a bad file would raise.
- Explain from the documentation what Settings.Default.Save writes and where.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which call opens a form without waiting for it?
Answer
Show()
Show returns at once; ShowDialog blocks until the form closes.
-
What does Owner do to two windows?
Answer
Keeps the owned form above its owner, and closes it with the owner
An owned palette minimises and closes with its editor.
-
Which property makes a form an MDI parent?
Answer
IsMdiContainer = true
Each child sets MdiParent to that parent.
-
Which call arranges the MDI children in a cascade?
Answer
LayoutMdi(MdiLayout.Cascade)
MdiLayout has Cascade, TileHorizontal and TileVertical.
-
What does MdiWindowListItem do?
Answer
Fills the named menu item with the open documents
It is the feature that made MDI useful.
-
Which scope of Properties.Settings can the application write?
Answer
User
Application scope is read-only and shared.
-
Where does Properties.Settings keep the user's values?
Answer
In the user's profile, under LOCALAPPDATA
That is why a per-user setting survives an update of the program.
-
Which line of the run shows the defaults?
Answer
the one printing 9 pt and 0 recent from a new AppSettings
The defaults live in the property initialisers of the class.
-
Why should a settings read be wrapped in a try?
Answer
The file is user-editable and will eventually be corrupt
A corrupt file must not stop the application from starting.
-
When is a palette the right choice over a modal dialog?
Answer
When the user must work in the main window at the same time
A palette is modeless by definition; a question is modal.
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