ContextMenuStrip and NotifyIcon

Two menus do not belong to the menu bar. A ContextMenuStrip appears at the pointer on a right click and belongs to the control it was assigned to; a NotifyIcon puts an icon in the notification area of the task bar, with a menu of its own. They share the item types of the menu bar, and both are about the same problem: a menu whose items depend on where it was opened.

A menu at the pointer

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 ListBox _files = new() { Dock = DockStyle.Fill }; public Form1() { Text = "Right-click a file"; ClientSize = new Size(360, 220); _files.Items.AddRange(new object[] { "notes.txt", "ideas.txt", "todo.txt" }); var menu = new ContextMenuStrip(); menu.Items.Add("&Open", null, (sender, e) => ShowName("open")); menu.Items.Add("&Rename", null, (sender, e) => ShowName("rename")); menu.Items.Add("&Delete", null, (sender, e) => ShowName("delete")); menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("Select &all", null, (sender, e) => ShowName("select all")); menu.Opening += (sender, e) => { var onItem = _files.SelectedIndex >= 0; for (var i = 0; i < 3; i++) { menu.Items[i].Enabled = onItem; } if (menu.SourceControl != _files) { e.Cancel = true; } }; _files.ContextMenuStrip = menu; Controls.Add(_files); } private void ShowName(string action) { var name = _files.SelectedItem as string ?? "nothing"; Text = $"{action}: {name}"; } }

dotnet build app.csproj

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

The listing is built and not run. ContextMenuStrip is assigned to the control, and the framework shows it at the pointer on a right click without a line of code. The Opening handler is where the menu becomes about this click: it disables the three commands when no row is selected, and it cancels the menu altogether when the source is not the list. SourceControl is the control the menu was opened on, which is how one menu serves several controls with different items.

A menu that is shown from code uses Show(control, point), with the point in the coordinates of that control. The Opening event fires for that call too, so the two routes share the same state logic.

The Opening event

A context menu with five commands and no Opening handler is a menu that offers Open and Delete on an empty space. It is the most common defect of a list view, and the event is the whole answer.

NotifyIcon

A tray icon is a component, not a control: it has no place on the form and no size. It needs an icon, a short text and a menu, and it lives until it is disposed:

using System; using System.Drawing; using System.Windows.Forms; internal sealed class Form1 : Form { private readonly NotifyIcon _tray = new(); public Form1() { Text = "Notes, running in the tray"; ClientSize = new Size(420, 200); var menu = new ContextMenuStrip(); menu.Items.Add("&Show", null, (sender, e) => Restore()); menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("E&xit", null, (sender, e) => Close()); _tray.Icon = SystemIcons.Application; _tray.Text = "Notes"; _tray.Visible = true; _tray.ContextMenuStrip = menu; _tray.BalloonTipTitle = "Notes is running"; _tray.BalloonTipText = "The icon stays here while the window is closed."; _tray.BalloonTipIcon = ToolTipIcon.Info; _tray.DoubleClick += (sender, e) => Restore(); _tray.ShowBalloonTip(3000); Resize += (sender, e) => { if (WindowState == FormWindowState.Minimized) { Hide(); } }; FormClosed += (sender, e) => _tray.Dispose(); } private void Restore() { Show(); WindowState = FormWindowState.Normal; Activate(); } }

That block is a fragment: a form with no Main, so the checker counts it and does not build it. Four rules of a tray application are in it. Text is the tooltip of the icon and is limited to 63 characters. Visible = true is what makes the icon appear at all. The form is hidden rather than closed when it is minimised, so the application keeps running with no window. And the icon is disposed in FormClosed, because an icon that outlives its process leaves a ghost in the tray until the pointer passes over it.

The tray menu and the balloon tip are the two ways a tray application talks to the user. A third is a ToolTipIcon on the balloon, which decides the picture: Info, Warning, Error or None. Windows 10 and later may show the balloon as a notification instead, and a system setting can suppress it; a message that must arrive belongs in the window, not in the balloon.

A context menu that runs

Which items a menu offers is a function of what was clicked, and that function runs here:

using System; using System.Collections.Generic; var menu = new ContextBuilder(); foreach (var selection in new[] { 0, 1, 3 }) { Console.WriteLine($"selection {selection}: {string.Join(", ", menu.Build(selection))}"); } Console.WriteLine($"items for none: {menu.Build(0).Count}"); internal sealed class ContextBuilder { public IReadOnlyList<string> Build(int selectedRows) => selectedRows switch { 0 => new[] { "Paste", "Select all" }, 1 => new[] { "Open", "Rename", "Delete", "Select all" }, _ => new[] { "Open", "Rename", $"Delete {selectedRows} items", "Select all" }, }; }

dotnet run

selection 0: Paste, Select all
selection 1: Open, Rename, Delete, Select all
selection 3: Open, Rename, Delete 3 items, Select all
items for none: 2

The output is the real run. An empty selection offers the two commands that do not need a row, one row offers the four that do, and three rows name the number, which is the caption a real menu uses for a bulk delete. A form builds the same list in Opening and either sets Enabled on fixed items or rebuilds Items; the rebuild is the honest choice when the set of commands itself changes, because a disabled item that never becomes enabled is clutter.

Exercises

  1. Add a fifth selection case for a locked row and run the program.
  2. Change Build to return items with an enabled flag, and print the disabled ones in brackets.
  3. Explain from the documentation what ShowBalloonTip does when two calls happen in a row.

Questions

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

  1. How does a control get a right-click menu?

    Answer

    Assign a ContextMenuStrip to its ContextMenuStrip property

    The framework shows it at the pointer; Show is for the manual route.

  2. Which event builds the items for what was clicked?

    Answer

    Opening

    It fires before the menu appears, for both a right click and Show.

  3. What does e.Cancel = true in Opening do?

    Answer

    Stops the menu from appearing

    It is how a shared menu refuses a click it does not apply to.

  4. What is SourceControl?

    Answer

    The control the menu was opened on

    It lets one menu serve several controls.

  5. What does NotifyIcon.Visible = true do?

    Answer

    Puts the icon in the notification area

    Without it the icon exists and is never shown.

  6. How long may NotifyIcon.Text be?

    Answer

    63 characters

    It is the tooltip of the icon, and the limit is documented.

  7. Why is a tray icon disposed in FormClosed?

    Answer

    An icon that outlives its process leaves a ghost in the tray

    The ghost stays until the pointer passes over it.

  8. What did the run print for a selection of three rows?

    Answer

    Open, Rename, Delete 3 items, Select all

    The caption names the number of rows.

  9. Which property hides an item but keeps it in the collection?

    Answer

    Available = false

    Enabled greys it out; Available removes it from the menu without removing the object.

  10. Why can a balloon tip not carry a message that must arrive?

    Answer

    Windows may show it as a notification or suppress it by a system setting

    The window is the surface that is certainly seen.

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