23
Lesson 23 of 35 ยท WinForms

Dialogs, Menus & Toolbars

Professional applications need menus, toolbars, status bars, and common dialogs. This lesson covers MenuStrip, ToolStrip, StatusStrip, and the built-in dialog boxes (OpenFileDialog, SaveFileDialog, ColorDialog, FontDialog).

MenuStrip

Drag a MenuStrip from the Toolbox onto your form. Click the strip to type menu items. Each item generates a Click event when double-clicked. Set ShortcutKeys to add keyboard shortcuts.

File menu handler MenuDemo.cs
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    using var dlg = new OpenFileDialog
    {
        Filter = "Text files|*.txt|All files|*.*",
        Title  = "Open a text file"
    };

    if (dlg.ShowDialog() == DialogResult.OK)
    {
        string content = File.ReadAllText(dlg.FileName);
        txtEditor.Text = content;
        this.Text = Path.GetFileName(dlg.FileName);
    }
}

ToolStrip & StatusStrip

A ToolStrip hosts buttons, combo boxes, and separators. A StatusStrip shows status information at the bottom of the form using ToolStripStatusLabel items.

ColorDialog & FontDialog

Use ColorDialog to let users pick a colour and FontDialog to pick a font.

Color and Font dialogs Dialogs.cs
private void btnColor_Click(object sender, EventArgs e)
{
    using var dlg = new ColorDialog();
    if (dlg.ShowDialog() == DialogResult.OK)
        txtEditor.BackColor = dlg.Color;
}

private void btnFont_Click(object sender, EventArgs e)
{
    using var dlg = new FontDialog { Font = txtEditor.Font };
    if (dlg.ShowDialog() == DialogResult.OK)
        txtEditor.Font = dlg.Font;
}