Skip to content
Tutorials Center
My learning

Topics

Lesson 169 of 182 ยท Advanced C#

Windows Forms Controls and Properties

Learn the core ideas of C# Windows Forms - Form, Label, TextBox and Button properties, event handlers, layout and anchoring - with read-only WinForms code and runnable console stand-ins.

Windows Forms (WinForms) is the classic .NET desktop UI framework: you drop controls such as buttons and text boxes on a window, set their properties, and write event handlers that run when the user clicks or types. It ships with modern .NET on Windows (the net10.0-windows target), and a huge amount of business software still uses it. If you want a modern look and cross-platform reach, see WPF and MAUI; if you want a quick internal tool on Windows, WinForms is still the fastest way to get one on screen.

Our online editor cannot open windows, and WinForms itself only runs on Windows. So this lesson uses two kinds of code. Read-only blocks show the real WinForms API. Runnable blocks build a tiny console stand-in with the same shape (controls, properties, events), so you can run and change the logic that matters: how controls store state and how an event reaches your handler.

The shape of a WinForms program

A WinForms app has an entry point that starts a message loop and a Form subclass that describes the window. This is the real thing (read-only):

C#
// Read-only: needs Windows and the Windows Forms workload.
using System.Windows.Forms;

internal static class Program
{
    [STAThread]
    private static void Main()
    {
        ApplicationConfiguration.Initialize();   // DPI, fonts, visual styles
        Application.Run(new MainForm());         // starts the message loop
    }
}

public class MainForm : Form
{
    public MainForm()
    {
        Text = "Hello WinForms";                 // title bar
        ClientSize = new Size(320, 160);
        StartPosition = FormStartPosition.CenterScreen;
    }
}

[STAThread] marks the main thread as a single-threaded apartment, which many Windows UI components require. Application.Run processes mouse and keyboard messages until the main form closes.

Control, the base class of everything

Every visible item inherits from System.Windows.Forms.Control: Form, Label, TextBox, Button, CheckBox, ListBox and so on. That is why they share so many properties:

Property Meaning
Name The identifier used in code (txtUser, btnSave). Not shown to the user.
Text The caption, label text, or the text typed in a text box.
Location Position of the top-left corner (new Point(x, y)), relative to the parent.
Size, Width, Height Dimensions in pixels.
Font Typeface, size and style.
ForeColor, BackColor Text and background colors.
Enabled, Visible Whether it accepts input; whether it is drawn at all.
TabIndex, TabStop Order and eligibility when the user presses Tab.
Anchor, Dock How it moves or stretches when the form is resized.

Each concrete control adds its own: TextBox.PasswordChar, TextBox.MaxLength, TextBox.Multiline, Label.AutoSize, Button.DialogResult, CheckBox.Checked, and many more.

Building a login form in code

Visual Studio's designer writes code like this for you, in a file called MainForm.Designer.cs. Reading it once shows there is no magic:

C#
// Read-only: a login form built without the designer.
public class LoginForm : Form
{
    private readonly Label lblUser = new();
    private readonly TextBox txtUser = new();
    private readonly Label lblPassword = new();
    private readonly TextBox txtPassword = new();
    private readonly Button btnLogin = new();
    private readonly Label lblStatus = new();

    public LoginForm()
    {
        Text = "Sign in";
        ClientSize = new Size(300, 190);
        FormBorderStyle = FormBorderStyle.FixedDialog;   // not resizable
        MaximizeBox = false;

        lblUser.Text = "User name:";
        lblUser.Location = new Point(16, 20);
        lblUser.AutoSize = true;

        txtUser.Name = "txtUser";
        txtUser.Location = new Point(110, 16);
        txtUser.Width = 170;
        txtUser.MaxLength = 20;

        lblPassword.Text = "Password:";
        lblPassword.Location = new Point(16, 56);
        lblPassword.AutoSize = true;

        txtPassword.Name = "txtPassword";
        txtPassword.Location = new Point(110, 52);
        txtPassword.Width = 170;
        txtPassword.PasswordChar = '*';                  // show * instead of the text
        txtPassword.UseSystemPasswordChar = false;

        btnLogin.Text = "Log in";
        btnLogin.Location = new Point(110, 92);
        btnLogin.Font = new Font("Segoe UI", 10f, FontStyle.Bold);
        btnLogin.BackColor = Color.SteelBlue;
        btnLogin.ForeColor = Color.White;
        btnLogin.Click += BtnLogin_Click;                 // wire the event

        lblStatus.Location = new Point(16, 140);
        lblStatus.AutoSize = true;

        Controls.AddRange(new Control[] { lblUser, txtUser, lblPassword, txtPassword, btnLogin, lblStatus });
        AcceptButton = btnLogin;                          // Enter presses it
    }

    private void BtnLogin_Click(object? sender, EventArgs e)
    {
        if (txtUser.Text.Trim().Length == 0)
        {
            lblStatus.ForeColor = Color.Firebrick;
            lblStatus.Text = "Please enter a user name.";
            txtUser.Focus();
            return;
        }

        lblStatus.ForeColor = Color.SeaGreen;
        lblStatus.Text = $"Welcome, {txtUser.Text}!";
    }
}

Three things are worth noticing. A form owns its controls through the Controls collection, and adding a control to that collection is what makes it appear. Location and Size use the Point and Size structs from System.Drawing. And btnLogin.Click += BtnLogin_Click; subscribes a method to an event, exactly the same C# feature you learned earlier; the handler receives the sender (the button) and an EventArgs object.

How controls and events work, in plain C#

The next program rebuilds that idea without a window. A base Control class stores Name, Text, Location, Enabled and Visible; Button raises a Click event; TextBox has PasswordChar and MaxLength; a Form owns a collection of controls. We "click" the button by calling a method, as the Windows message loop would after a mouse click. Change the values and re-run it to explore.

C# A console stand-in for WinForms controls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The pieces map one to one: Controls.Add is how a real form gets children, PerformClick is a stand-in for the mouse, and += wires the handler. One difference to remember: in real WinForms, MaxLength limits what the user can type, but text you assign from code is not cut. The stand-in is stricter so you can see the property work.

Layout: Anchor, Dock and containers

Hard-coded Location values break when a user resizes the window. WinForms offers three tools:

  • Anchor keeps a control a fixed distance from chosen edges. A text box anchored Top | Left | Right stretches horizontally when the form widens.
  • Dock glues a control to an edge (Top, Bottom, Left, Right) or fills the remaining space (Fill).
  • Layout containers (FlowLayoutPanel, TableLayoutPanel, SplitContainer, GroupBox) arrange their children for you.
C#
// Read-only: a resizable form with a status bar and a filling editor.
var editor = new TextBox { Multiline = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical };
var status = new StatusStrip { Dock = DockStyle.Bottom };
status.Items.Add(new ToolStripStatusLabel("Ready"));
Controls.Add(editor);
Controls.Add(status);

var okButton = new Button { Text = "OK", Anchor = AnchorStyles.Bottom | AnchorStyles.Right };

Use docking and table layouts for anything beyond a prototype; absolute coordinates are fine for tiny dialogs.

Common events

Event Raised when
Click, DoubleClick The mouse clicks the control
TextChanged Text changes (every key press in a text box)
KeyDown, KeyPress A key is pressed while the control has focus
Load (Form) The form is about to be shown for the first time
FormClosing The user closes the form; set e.Cancel = true to refuse
Validating Focus leaves a control; a place for input checks

The handlers all follow the standard .NET event pattern (object? sender, EventArgs e) shown above. The observer and MVVM lesson describes how this idea scales to bigger apps.

Good habits

  • Name controls meaningfully (txtEmail, not textBox1) before you write handlers.
  • Keep logic out of handlers. A handler should read the controls, call a normal class that does the real work (and that you can unit test), and show the result.
  • Never block the UI thread. A long database call in a Click handler freezes the window. Use async/await with Task.Run or an async API so the message loop keeps running.
  • Dispose forms and controls you create outside the designer, or wrap them in using.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which base class do Form, Label, TextBox and Button all inherit from?

    Control defines the shared properties such as Name, Text, Location, Size, Font, Enabled and Visible.
  2. 2. How do you make a TextBox show * for each typed character?

    PasswordChar masks the display while the real text is still available in Text.
  3. 3. What does btnSave.Click += OnSave; do?

    The += operator adds a handler to an event. The method runs whenever the button is clicked.
  4. 4. Which setting makes a TextBox fill the remaining space of its parent?

    DockStyle.Fill stretches the control to use all the space not taken by other docked controls.

Summary

  • WinForms builds windows from Control-derived classes owned by a Form's Controls collection.
  • Common properties (Name, Text, Location, Size, Font, ForeColor, Enabled, Visible) live on Control; each control type adds its own.
  • Events such as Click and TextChanged use ordinary C# events with (sender, e) handlers.
  • Use Anchor, Dock and layout panels for resizable windows; keep handlers thin and the UI thread free.
  • Our editor cannot show windows, so the real WinForms code is read-only and the console stand-in teaches the object model.

Next: compare with the XAML-based frameworks in WPF and MAUI, or see the observer pattern and MVVM.