A form written by hand
A Form is a window: a rectangular area with a title bar, a border, and a client area that belongs to your controls. Everything the designer does, it does by setting properties and calling Controls.Add, so a form written by hand is the same form. This lesson writes one in code, which is the version the rest of the course checks.
A window is an object
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
{
public Form1()
{
Text = "Notes";
ClientSize = new Size(640, 480);
StartPosition = FormStartPosition.CenterScreen;
FormBorderStyle = FormBorderStyle.Sizable;
MinimumSize = new Size(400, 300);
MaximizeBox = true;
BackColor = Color.White;
var editor = new TextBox
{
Multiline = true,
Dock = DockStyle.Fill,
ScrollBars = ScrollBars.Vertical,
PlaceholderText = "Start typing",
};
Controls.Add(editor);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The program is built and not run: there is no desktop here to show the window on. What it would do is documented behaviour: a window 640 by 480 pixels in its client area, centred on the screen, resizable down to 400 by 300, with a white background and one text box filling it.
The properties that matter first
- Text: the caption in the title bar and the name in the task bar.
- ClientSize against Size: ClientSize is the area your controls live in; Size includes the border and the title bar, so it is larger by a few dozen pixels that depend on the theme and the DPI.
- StartPosition: CenterScreen, CenterParent or Manual with Location. The default is WindowsDefaultLocation, which the window manager chooses.
- FormBorderStyle: Sizable (the default), FixedSingle for a dialog that must not resize, None for a splash screen, FixedToolWindow for a small floating palette.
- MinimumSize: the smallest the user can drag the window to. Without it, a resizable form can be dragged until its controls overlap.
- BackColor: a System.Drawing.Color. A control that sets its own background keeps it; Color.White on the form does not flow into a Button.
One property of Form is worth knowing early: AcceptButton. Setting it to a button makes the Enter key press that button, which is what a user expects in a dialog. CancelButton does the same for Escape.
Load and Shown
Three events mark the beginning of a form's life, and they fire in this order:
- Load: the form exists but is not visible yet. The place to fill a list or read a file that should be ready before the window appears.
- Shown: the window is visible for the first time. The place for work that needs a visible window, such as focusing a control or measuring a rendered size.
- Activated: the form became the active window. It fires again every time the user returns to it, unlike the other two.
using System;
using System.Windows.Forms;
internal sealed class Form1 : Form
{
private readonly ListBox _recent = new() { Dock = DockStyle.Fill };
public Form1()
{
Text = "Recent files";
Controls.Add(_recent);
Load += OnLoad;
Shown += OnShown;
}
private void OnLoad(object? sender, EventArgs e)
{
_recent.Items.Add("notes.txt");
_recent.Items.Add("ideas.txt");
}
private void OnShown(object? sender, EventArgs e)
{
_recent.Focus();
}
}
That listing is a fragment: a form without Main, so the checker counts it and does not build it. It is half of a program, the half the designer writes, and lesson 006 shows both halves as the designer leaves them.
An initialiser or a constructor
The two listings above show the two styles that are both current. An object initialiser sets the properties from outside:
using System;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
var form = new Form
{
Text = "A quick window",
ClientSize = new Size(420, 200),
StartPosition = FormStartPosition.CenterScreen,
FormBorderStyle = FormBorderStyle.FixedDialog,
MaximizeBox = false,
MinimizeBox = false,
};
form.Controls.Add(new Label { Text = "Nothing here yet", AutoSize = true, Location = new Point(16, 16) });
Application.Run(form);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
A class that inherits from Form does the same work in its constructor, which is what the designer writes and what this course uses from here on. The difference is not style: a form that owns a field for each control can reach those controls in its handlers, and the designer depends on that shape. The next lesson reads a designer file line by line.
Exercises
- Set Size instead of ClientSize and explain why the client area becomes smaller than 640 by 480.
- Add Icon to a form. Which file type does the property take, and what does the compiler need to embed it?
- Set FormBorderStyle to None and describe how a user moves such a window.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does ClientSize measure?
Answer
The area the controls live in, without the border and the title bar
Size includes the non-client area; ClientSize is what your layout fills.
-
Which value centres a form on the screen?
Answer
StartPosition = FormStartPosition.CenterScreen
CenterScreen is one of the StartPosition values; Manual needs a Location.
-
Which FormBorderStyle makes a dialog that cannot be resized?
Answer
FixedDialog or FixedSingle
The fixed styles remove the resize grip; Sizable is the default.
-
Why set MinimumSize on a resizable form?
Answer
So the user cannot drag it until the controls overlap
It is the smallest size the window manager allows the user to drag to.
-
Which event fires when the form is visible for the first time?
Answer
Shown
Load runs before the window is visible; Shown runs after it is first shown.
-
Which event fires every time the user returns to the form?
Answer
Activated
Load and Shown fire once; Activated fires on every activation.
-
Which property makes Enter press a button?
Answer
AcceptButton
AcceptButton is the default button of the form; CancelButton answers Escape.
-
What does Controls.Add do?
Answer
Puts a control on the form and makes the form its parent
The parent owns the control, draws it and passes messages to it.
-
Which of the two styles does the designer write?
Answer
A class that inherits Form, with a field per control and a constructor
The designer's Form1.cs and Form1.Designer.cs are two halves of such a class.
-
Why is the program with the Label listing built and not run here?
Answer
There is no Windows desktop or Windows Desktop runtime in the container
WinForms draws through the Windows desktop APIs; the compiler is all this machine can offer.
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.
Article author: Arthur Isaev