MenuStrip

A MenuStrip is the main menu of a window: File, Edit, View, Help, each with a list behind it. It docks itself to the top of the form and takes the height it needs, and it is a ToolStrip in disguise, which is why the item class is called ToolStripMenuItem and why a menu item and a toolbar button share a base class.

A menu on a form

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 _editor = new() { Dock = DockStyle.Fill }; private readonly ToolStripMenuItem _wordWrap = new("&Word wrap") { CheckOnClick = true, Checked = true }; public Form1() { Text = "Notes"; ClientSize = new Size(520, 320); var menu = new MenuStrip(); var file = new ToolStripMenuItem("&File"); file.DropDownItems.Add(new ToolStripMenuItem("&New", null, OnNew) { ShortcutKeys = Keys.Control | Keys.N }); file.DropDownItems.Add(new ToolStripMenuItem("&Open...", null, OnOpen) { ShortcutKeys = Keys.Control | Keys.O }); file.DropDownItems.Add(new ToolStripMenuItem("&Save", null, OnSave) { ShortcutKeys = Keys.Control | Keys.S }); file.DropDownItems.Add(new ToolStripSeparator()); file.DropDownItems.Add(new ToolStripMenuItem("E&xit", null, (sender, e) => Close())); var view = new ToolStripMenuItem("&View"); view.DropDownItems.Add(_wordWrap); menu.Items.Add(file); menu.Items.Add(view); MainMenuStrip = menu; Controls.Add(_editor); Controls.Add(menu); } private void OnNew(object? sender, EventArgs e) => _editor.Clear(); private void OnOpen(object? sender, EventArgs e) => _editor.Text = "opened"; private void OnSave(object? sender, EventArgs e) => _editor.Text = "saved"; }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. The menu is two top-level items and four commands, one of them a separator and one a toggle. Three details are worth reading out of it. The ampersands in &File make Alt+F open the menu, and the same character works in every item of it. ShortcutKeys registers the key with the form's input processing, so Ctrl+S presses the item even when the editor has the focus and the menu is closed. And MainMenuStrip tells the form which menu handles the access keys; without it a second menu bar would be decoration.

The items

A menu whose items are enabled by hand in ten places is a menu that will be wrong in at least one of them. The pattern that survives is the one in the next section: the item asks a command whether it can run, at the moment the menu opens.

One command, three controls

A command is an object with a name, a shortcut and a method, and the menu item, the toolbar button and the shortcut all call the same one. WinForms does not ship a command class; the C# course builds the same thing for a console program, and a form adds the two states a control needs:

using System; using System.Windows.Forms; internal sealed class Form1 : Form { private readonly ToolStripMenuItem _saveItem = new("&Save") { ShortcutKeys = Keys.Control | Keys.S }; private readonly ToolStripButton _saveButton = new("Save"); private bool _dirty; public Form1() { _saveItem.Click += (sender, e) => Save(); _saveButton.Click += (sender, e) => Save(); var file = new ToolStripMenuItem("&File"); file.DropDownItems.Add(_saveItem); file.DropDownOpening += (sender, e) => _saveItem.Enabled = _dirty; var menu = new MenuStrip(); menu.Items.Add(file); MainMenuStrip = menu; var bar = new ToolStrip(); bar.Items.Add(_saveButton); Controls.Add(menu); Controls.Add(bar); } private void Save() { _dirty = false; Text = "saved"; } }

That block is a fragment: a form with no Main, so the checker counts it and does not build it. The state lives in one field, _dirty, and each surface reads it at the moment it is shown: the menu in DropDownOpening, the toolbar in ItemClicked or not at all. A form that also disables the shortcut has to decide what a shortcut does while the command cannot run, and the simplest answer is that Save returns early when there is nothing to save.

The command table that runs

The list of commands and their states is data, and the state of every item is computed from it. This program prints the menu a form would build, and it runs here:

using System; using System.Collections.Generic; var commands = new List<Command> { new("New", "Ctrl+N", CanExecute: true), new("Save", "Ctrl+S", CanExecute: false), new("Export", string.Empty, CanExecute: true), }; foreach (var command in commands) { var state = command.CanExecute ? "enabled" : "disabled"; var key = command.Shortcut.Length == 0 ? "no shortcut" : command.Shortcut; Console.WriteLine($"{command.Name,-7} {key,-11} {state}"); } Console.WriteLine($"runnable: {commands.FindAll(command => command.CanExecute).Count}"); internal sealed record Command(string Name, string Shortcut, bool CanExecute);

dotnet run

New     Ctrl+N      enabled
Save    Ctrl+S      disabled
Export  no shortcut enabled
runnable: 2

The output is the real run. The row for Export has no shortcut and says so, which is the case a menu item shows as a shorter row; the count is what a toolbar loops over to decide which buttons are enabled. The table is the same one the menu and the toolbar read, which is the point of the pattern: one place decides what a command is called, what key presses it and whether it can run, and the three controls are views of that decision.

Exercises

  1. Add a fourth command with the shortcut Ctrl+Shift+F5 and run the program.
  2. Make the state a second value, such as a tick instead of disabled, and print a table with three columns.
  3. Explain from the documentation what DropDownOpening is for and why Enable should not be set in the constructor alone.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which class is a menu item?

    Answer

    ToolStripMenuItem

    A MenuStrip is a ToolStrip, so its items derive from the tool-strip item.

  2. Which property gives an item a keyboard shortcut?

    Answer

    ShortcutKeys, a Keys value

    The ampersand is the Alt access key; ShortcutKeys is the Ctrl combination.

  3. What does the ampersand in "&File" do?

    Answer

    Makes Alt+F open that menu

    It is the same access-key rule as a label or a button.

  4. Which property makes an item toggle with a click?

    Answer

    CheckOnClick, with Checked

    CheckState adds the indeterminate third state.

  5. Where should a menu enable its items?

    Answer

    In DropDownOpening, at the moment it is shown

    The state changes while the form is open, so it must be read when the menu opens.

  6. What does MainMenuStrip do?

    Answer

    Names the menu that handles the form's access keys

    Without it a second menu bar would not answer Alt.

  7. What does a separator look like in code?

    Answer

    new ToolStripSeparator() added to DropDownItems

    It is the line between groups of items.

  8. What did the run print for Export?

    Answer

    no shortcut, enabled

    Its shortcut string is empty and its CanExecute is true.

  9. Why is one command object better than three handlers?

    Answer

    One place decides the name, the key and whether it can run

    The menu, the toolbar and the shortcut become views of one decision.

  10. Which property lists the open child windows in an MDI application?

    Answer

    MdiWindowListItem

    The menu item it names is filled with the child forms.

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