ZetCode

C# Windows Forms

last modified November 15, 2026

This tutorial is a hands-on introduction to GUI programming with C# and Windows Forms. Instead of the visual Form designer, we build the user interfaces in code, which shows how the framework works underneath.

Windows Forms

Windows Forms, often called WinForms, is a framework for building Windows desktop applications. It wraps the native Win32 controls and provides buttons, labels, text boxes, menus, dialogs, layout panels, and a drawing API in the System.Windows.Forms and System.Drawing namespaces.

Windows Forms was released with the first .NET Framework in 2002. In December 2018 Microsoft open-sourced it under the MIT license and ported it to .NET Core. Current versions ship with every .NET release, but the framework runs only on Windows.

Creating a Windows Forms project

A new project is created with the dotnet new winforms template. It targets the net10.0-windows framework. The template also creates Form1.cs and Form1.Designer.cs for the designer; we do not use them and delete them. Each example in this tutorial replaces the generated Program.cs file.

First.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net10.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>

The UseWindowsForms property adds the Windows Forms libraries. With ImplicitUsings enabled, the System.Drawing and System.Windows.Forms namespaces are imported automatically, so the examples need no using directives. The WinExe output type means that no console window is opened along with the application.

The examples were built with .NET 10. The screenshots were taken with Wine on Linux, so the window frames look different from those on Windows 11.

$ dotnet new winforms -o First
$ cd First
$ rm Form1.cs Form1.Designer.cs
$ dotnet run

Simple window

In the first example, we show a small window in the middle of the screen.

Program.cs
namespace First;

public class MyForm : Form
{
    public MyForm()
    {
        InitComponents();
    }

    private void InitComponents()
    {
        Text = "First application";
        ClientSize = new Size(600, 350);
        StartPosition = FormStartPosition.CenterScreen;
    }

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new MyForm());
    }
}

The example displays an empty main window.

public class MyForm : Form

In Windows Forms, every window and dialog is a Form. It is a container that hosts child controls. MyForm inherits from Form and thus becomes a window itself.

Text = "First application";
ClientSize = new Size(600, 350);
StartPosition = FormStartPosition.CenterScreen;

The Text property sets the title of the window and ClientSize the size of its client area, which excludes the title bar and borders. With FormStartPosition.CenterScreen, the window appears in the center of the screen. (The CenterToScreen method has the same effect, but the documentation advises against calling it directly.)

[STAThread]
static void Main()

The Main method is the entry point of the application. Windows Forms requires the single-threaded apartment model, which the [STAThread] attribute selects. Without it, the clipboard, drag and drop, and common dialogs do not work correctly.

ApplicationConfiguration.Initialize();

ApplicationConfiguration.Initialize is generated by a source generator at build time. It enables visual styles, sets the high DPI mode (SystemAware by default), and applies other settings from the project file. It replaces the separate EnableVisualStyles and SetHighDpiMode calls of older code.

Application.Run(new MyForm());

The Run method shows the form and starts the message loop on the current thread. It returns when the form is closed.

Simple window
Figure: Simple window

Tooltips

A tooltip is a small pop-up window that describes a control when the mouse pointer rests on it.

Program.cs
namespace Tooltips;

public class MyForm : Form
{
    public MyForm()
    {
        InitComponents();
    }

    private void InitComponents()
    {
        Text = "Tooltips";
        ClientSize = new Size(450, 250);
        StartPosition = FormStartPosition.CenterScreen;

        var flowPanel = new FlowLayoutPanel
        {
            Dock = DockStyle.Fill,
            Padding = new Padding(10)
        };

        var button1 = new Button { Text = "Button", AutoSize = true };
        var button2 = new Button { Text = "Button 2", AutoSize = true };

        var tooltip = new ToolTip();
        tooltip.SetToolTip(flowPanel, "This is a FlowLayoutPanel");
        tooltip.SetToolTip(button1, "This is a Button control");

        flowPanel.Controls.Add(button1);
        flowPanel.Controls.Add(button2);
        Controls.Add(flowPanel);
    }

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new MyForm());
    }
}

We add tooltips to a panel and a button.

var flowPanel = new FlowLayoutPanel
{
    Dock = DockStyle.Fill,
    Padding = new Padding(10)
};

A FlowLayoutPanel lays out its children one after another, left to right by default, and wraps them to the next row when needed. With DockStyle.Fill, the panel fills the whole client area. We set the properties with object initializers.

var button1 = new Button { Text = "Button", AutoSize = true };

With AutoSize, the button grows to fit its text.

var tooltip = new ToolTip();
tooltip.SetToolTip(flowPanel, "This is a FlowLayoutPanel");
tooltip.SetToolTip(button1, "This is a Button control");

One ToolTip component can serve many controls. The SetToolTip method assigns a text to each of them. The second button has no tooltip.

flowPanel.Controls.Add(button1);
flowPanel.Controls.Add(button2);
Controls.Add(flowPanel);

The buttons are added to the panel and the panel is added to the form. The Controls collection defines the parent-child hierarchy of the controls.

Tooltip
Figure: Tooltip

Quit button

A Button is clicked with the mouse, or with the Enter or Spacebar key when it has focus. The click is reported by the Click event.

Program.cs
namespace QuitButton;

public class MyForm : Form
{
    public MyForm()
    {
        InitComponents();
    }

    private void InitComponents()
    {
        Text = "Quit button";
        ClientSize = new Size(450, 250);
        StartPosition = FormStartPosition.CenterScreen;

        var flowPanel = new FlowLayoutPanel { Dock = DockStyle.Fill };

        var button = new Button
        {
            Text = "Quit",
            AutoSize = true,
            Margin = new Padding(10, 10, 0, 0)
        };

        button.Click += (_, _) => Close();

        flowPanel.Controls.Add(button);
        Controls.Add(flowPanel);
    }

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new MyForm());
    }
}

The application terminates when we click the button.

Margin = new Padding(10, 10, 0, 0)

The margin puts some space to the left of and above the button.

button.Click += (_, _) => Close();

We attach a lambda to the Click event. It calls the Close method of the form; closing the main form ends the application. We do not need the sender and the event arguments, so we use discards for both parameters.

Quit button
Figure: Quit button

Label

A Label displays text or an image. It does not receive focus.

Program.cs
namespace LabelEx;

public class MyForm : Form
{
    public MyForm()
    {
        InitComponents();
    }

    private void InitComponents()
    {
        string text = """
            I wandered lonely as a cloud
            That floats on high o'er vales and hills,
            When all at once I saw a crowd,
            A host, of golden daffodils;
            Beside the lake, beneath the trees,
            Fluttering and dancing in the breeze.

            William Wordsworth, 1807
            """;

        var poem = new Label
        {
            Text = text,
            Font = new Font("Georgia", 11),
            Location = new Point(15, 15),
            AutoSize = true
        };

        Controls.Add(poem);

        Text = "Label";
        AutoSize = true;
        AutoSizeMode = AutoSizeMode.GrowAndShrink;
        Padding = new Padding(0, 0, 15, 15);
        StartPosition = FormStartPosition.CenterScreen;
    }

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new MyForm());
    }
}

The example displays a poem in a label. The window is sized to fit the text.

string text = """

The poem is a raw string literal. Its indentation is removed up to the column of the closing quotes.

var poem = new Label
{
    Text = text,
    Font = new Font("Georgia", 11),
    Location = new Point(15, 15),
    AutoSize = true
};

The label is placed at the x=15, y=15 coordinates of the client area. When the requested font is not installed, Windows substitutes a similar one.

AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
Padding = new Padding(0, 0, 15, 15);

The form sizes itself to its content. GrowAndShrink lets it also become smaller than its default size, and the padding leaves a margin to the right of and below the label.

Label
Figure: Label

CheckBox

A CheckBox is a control with two states: checked and unchecked. It is a box with a label; a checked box shows a tick.

Program.cs
namespace CheckBoxEx;

public class MyForm : Form
{
    public MyForm()
    {
        InitComponents();
    }

    private void InitComponents()
    {
        Text = "CheckBox";
        ClientSize = new Size(400, 200);
        StartPosition = FormStartPosition.CenterScreen;

        var flowPanel = new FlowLayoutPanel { Dock = DockStyle.Fill };

        var cb = new CheckBox
        {
            Text = "Show title",
            AutoSize = true,
            Checked = true,
            Margin = new Padding(20)
        };

        cb.CheckedChanged += OnChanged;

        flowPanel.Controls.Add(cb);
        Controls.Add(flowPanel);
    }

    private void OnChanged(object? sender, EventArgs e)
    {
        if (sender is CheckBox { Checked: true })
        {
            Text = "CheckBox";
        }
        else
        {
            Text = "";
        }
    }

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new MyForm());
    }
}

The check box shows or hides the title of the window.

var cb = new CheckBox
{
    Text = "Show title",
    AutoSize = true,
    Checked = true,
    Margin = new Padding(20)
};

The title is visible at the start, so the check box starts checked.

cb.CheckedChanged += OnChanged;

The CheckedChanged event fires whenever the state of the check box changes. We handle it with the OnChanged method.

private void OnChanged(object? sender, EventArgs e)
{
    if (sender is CheckBox { Checked: true })

The handler matches the EventHandler delegate. The sender is declared nullable, as the project has nullable reference types enabled. A property pattern checks that the sender is a checked CheckBox. Depending on the result, we set or clear the title.

CheckBox
Figure: CheckBox

TextBox

A TextBox lets the user enter and edit text. Its TextChanged event fires on every change.

Program.cs
namespace TextBoxEx;

public class MyForm : Form
{
    private readonly Label countLabel = new() { AutoSize = true };

    public MyForm()
    {
        InitComponents();
    }

    private void InitComponents()
    {
        Text = "TextBox";
        ClientSize = new Size(400, 150);
        StartPosition = FormStartPosition.CenterScreen;

        var layout = new TableLayoutPanel
        {
            Dock = DockStyle.Fill,
            Padding = new Padding(15),
            ColumnCount = 1
        };

        var nameBox = new TextBox
        {
            Dock = DockStyle.Top,
            PlaceholderText = "Enter your name"
        };

        nameBox.TextChanged += (_, _) => UpdateLabel(nameBox.Text);

        layout.Controls.Add(nameBox);
        layout.Controls.Add(countLabel);
        Controls.Add(layout);

        UpdateLabel("");
    }

    private void UpdateLabel(string name)
    {
        countLabel.Text = name.Length == 0
            ? "No name entered"
            : $"Hello {name}! ({name.Length} characters)";
    }

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new MyForm());
    }
}

The label below the text box greets the user and counts the characters as they type.

var layout = new TableLayoutPanel
{
    Dock = DockStyle.Fill,
    Padding = new Padding(15),
    ColumnCount = 1
};

A TableLayoutPanel arranges controls in a grid. With one column, the text box and the label are placed below each other.

var nameBox = new TextBox
{
    Dock = DockStyle.Top,
    PlaceholderText = "Enter your name"
};

The text box stretches across the cell. PlaceholderText is shown in gray while the box is empty.

nameBox.TextChanged += (_, _) => UpdateLabel(nameBox.Text);

On every change of the text, we update the label.

TextBox
Figure: TextBox

Simple menu

A menubar is a set of menus. A menu groups the commands of an application. In Windows Forms, the menubar is a MenuStrip and its menus and commands are ToolStripMenuItem objects.

Program.cs
namespace MenuEx;

public class MyForm : Form
{
    public MyForm()
    {
        InitComponents();
    }

    private void InitComponents()
    {
        Text = "Simple menu";
        ClientSize = new Size(450, 300);
        StartPosition = FormStartPosition.CenterScreen;

        var ms = new MenuStrip();

        var fileMenuItem = new ToolStripMenuItem("&File");
        var exitMenuItem = new ToolStripMenuItem("E&xit", null, (_, _) => Close());

        exitMenuItem.ShortcutKeys = Keys.Control | Keys.Q;
        fileMenuItem.DropDownItems.Add(exitMenuItem);

        ms.Items.Add(fileMenuItem);

        Controls.Add(ms);
        MainMenuStrip = ms;
    }

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new MyForm());
    }
}

We create a menubar with a File menu that has one Exit command.

var fileMenuItem = new ToolStripMenuItem("&File");

The ampersand marks the mnemonic: the menu opens with Alt+F.

var exitMenuItem = new ToolStripMenuItem("E&xit", null, (_, _) => Close());

The constructor takes the text, an image, and a click handler. The command closes the window.

exitMenuItem.ShortcutKeys = Keys.Control | Keys.Q;
fileMenuItem.DropDownItems.Add(exitMenuItem);

The command gets the Ctrl+Q shortcut, which works without opening the menu. The item is added to the drop-down list of the File menu.

Controls.Add(ms);
MainMenuStrip = ms;

The menu strip is added to the form like any other control. The MainMenuStrip property makes it the main menu of the form, which, for example, enables keyboard activation with the Alt key.

Simple menu
Figure: Simple menu

Painting rectangles

Custom drawing is done in the OnPaint method, or in a handler of the Paint event. The system calls it whenever a part of the window needs to be redrawn, for example after the window is uncovered or resized.

Program.cs
namespace RectanglesEx;

public class MyForm : Form
{
    public MyForm()
    {
        Text = "Rectangles";
        ClientSize = new Size(360, 270);
        StartPosition = FormStartPosition.CenterScreen;
        BackColor = Color.White;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        Graphics g = e.Graphics;

        g.FillRectangle(Brushes.Sienna, 10, 15, 90, 60);
        g.FillRectangle(Brushes.Green, 130, 15, 90, 60);
        g.FillRectangle(Brushes.Maroon, 250, 15, 90, 60);
        g.FillRectangle(Brushes.Chocolate, 10, 105, 90, 60);
        g.FillRectangle(Brushes.Gray, 130, 105, 90, 60);
        g.FillRectangle(Brushes.Coral, 250, 105, 90, 60);
        g.FillRectangle(Brushes.Brown, 10, 195, 90, 60);
        g.FillRectangle(Brushes.Teal, 130, 195, 90, 60);
        g.FillRectangle(Brushes.Goldenrod, 250, 195, 90, 60);
    }

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new MyForm());
    }
}

We draw nine rectangles in nine different colors.

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

A class derived from Form overrides the OnPaint method. Calling the base method raises the Paint event for any other subscribers.

Graphics g = e.Graphics;

The Graphics object is the drawing surface. Painting means calling its methods.

g.FillRectangle(Brushes.Sienna, 10, 15, 90, 60);

FillRectangle fills a rectangle with a brush. The Brushes class provides solid brushes for all named colors. The four numbers are the x and y coordinates of the top-left corner, the width, and the height.

Rectangles
Figure: Rectangles

Message boxes

Message boxes inform the user or ask for a decision. The static MessageBox.Show method shows a modal dialog with a text, a caption, buttons, and an icon, and returns the button the user chose as a DialogResult.

Program.cs
namespace MessageBoxEx;

public class MyForm : Form
{
    private readonly Label status = new() { AutoSize = true };

    public MyForm()
    {
        InitComponents();
    }

    private void InitComponents()
    {
        Text = "MessageBox";
        ClientSize = new Size(400, 200);
        StartPosition = FormStartPosition.CenterScreen;

        var flowPanel = new FlowLayoutPanel
        {
            Dock = DockStyle.Fill,
            FlowDirection = FlowDirection.TopDown,
            Padding = new Padding(10)
        };

        var infoBtn = new Button { Text = "Information", AutoSize = true };
        var errorBtn = new Button { Text = "Error", AutoSize = true };
        var askBtn = new Button { Text = "Question", AutoSize = true };

        infoBtn.Click += (_, _) => MessageBox.Show(this,
            "Download completed.", "Information",
            MessageBoxButtons.OK, MessageBoxIcon.Information);

        errorBtn.Click += (_, _) => MessageBox.Show(this,
            "Could not open the file.", "Error",
            MessageBoxButtons.OK, MessageBoxIcon.Error);

        askBtn.Click += (_, _) => AskQuestion();

        flowPanel.Controls.AddRange([infoBtn, errorBtn, askBtn, status]);
        Controls.Add(flowPanel);
    }

    private void AskQuestion()
    {
        DialogResult result = MessageBox.Show(this,
            "Do you want to save the changes?", "Question",
            MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

        status.Text = result switch
        {
            DialogResult.Yes => "Changes saved",
            DialogResult.No => "Changes discarded",
            _ => "Operation cancelled"
        };
    }

    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new MyForm());
    }
}

Three buttons open an information box, an error box, and a question. The label shows the answer to the question.

infoBtn.Click += (_, _) => MessageBox.Show(this,
    "Download completed.", "Information",
    MessageBoxButtons.OK, MessageBoxIcon.Information);

The first argument is the owner window. The dialog is centered over it and stays on top of it.

DialogResult result = MessageBox.Show(this,
    "Do you want to save the changes?", "Question",
    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

The question dialog has Yes, No, and Cancel buttons. Closing it with the Esc key or the close button counts as Cancel.

status.Text = result switch
{
    DialogResult.Yes => "Changes saved",
    DialogResult.No => "Changes discarded",
    _ => "Operation cancelled"
};

A switch expression turns the result into the text of the label.

Question message box
Figure: Question message box

Source

Windows Forms documentation

Form class - reference

In this article we have created simple GUI applications in C# with Windows Forms. See also the delegate and lambda expression tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.