Properties, tab order and access keys
Every control in WinForms derives from Control, and that base class is where the properties of this lesson live. They look trivial and decide most of what a user can do with a form: whether a field can be typed into, whether it is on the screen, in which order Tab reaches it, and which letter of a caption jumps to it.
The properties every control has
- Text: the caption of a label, button or form, the content of a text box, and empty for a control that shows no text.
- Name: the identifier the designer uses for the field and the key of Controls["name"]. It is not shown to the user and it is not required at run time, but a form built by hand keeps it for the same reason.
- Tag: an object the control carries for you. The usual use is an id: a row in a list box holds its database key in Tag, and the handler reads ((Control)sender).Tag instead of parsing the visible text.
- Enabled: false greys the control out, takes it out of the tab order and stops it raising input events. Setting it on a container disables everything inside.
- Visible: false hides the control and removes its space from the layout. A hidden control still exists and still holds its value.
- BackColor, ForeColor and Font: the appearance a control keeps unless a parent's colour flows down. A Button with visual styles on ignores BackColor unless FlatStyle changes.
- Cursor and Anchor/Dock: the pointer over the control, and the layout rules of the next part.
Name and Tag are the two that a form written by hand tends to forget, and both earn their place in the code behind it: a loop over Controls that clears the fields of a form reads Name in its error messages and Tag when it needs to know which record a control belongs to.
Tab order
Tab moves the focus from control to control in the order the container decides, and the container decides by TabIndex:
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 = "Tab order";
ClientSize = new Size(400, 200);
var nameLabel = new Label { Text = "&Name:", Location = new Point(16, 22), AutoSize = true, TabIndex = 0 };
var nameBox = new TextBox { Location = new Point(90, 18), Width = 200, TabIndex = 1 };
var codeLabel = new Label { Text = "&Code:", Location = new Point(16, 56), AutoSize = true, TabIndex = 2 };
var codeBox = new TextBox { Location = new Point(90, 52), Width = 200, TabIndex = 3 };
var notes = new TextBox { Location = new Point(16, 90), Size = new Size(360, 60), Multiline = true, TabIndex = 4 };
var save = new Button { Text = "&Save", Location = new Point(16, 160), TabIndex = 5 };
nameLabel.TabStop = false;
codeLabel.TabStop = false;
AcceptButton = save;
Controls.Add(nameLabel);
Controls.Add(nameBox);
Controls.Add(codeLabel);
Controls.Add(codeBox);
Controls.Add(notes);
Controls.Add(save);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. Tab reaches the name box, the code box, the notes and the Save button, in that order. A Label takes a TabIndex too, and with TabStop = false it is skipped: the number is only used to place the labels in the property grid's list, which is why the labels of a form are numbered with the field they describe.
A container numbers its own children separately. Tab enters a GroupBox through the child with the lowest TabIndex, visits them in that order, and only then leaves the group, so the TabIndex of the group box itself places the whole group among the form's controls. That is the rule the designer's Tab Order view draws arrows for: click each control in the order you want, and the designer renumbers.
Focus and ActiveControl
- Focus(): a request to give the control the focus. It returns false when the control cannot take it, which it cannot if it is disabled, hidden, not selectable or the form is not active.
- CanFocus: the question without the request.
- Select() and SelectNextControl(control, forward, tabStopOnly, nested, wrap): move the focus within a container without going through the operating system.
- ActiveControl: the child of a container that has the focus, which is how a form asks "which field was I in?" and how a dialog decides where to put the caret when it opens.
- ContainsFocus and Focused: whether this control, or a child of it, has the focus now.
A dialog sets ActiveControl in its constructor, or calls Focus() in Shown: before the form is visible, the focus cannot be given, and the call quietly fails. That is the most common reason a form opens with the focus in the wrong field.
Access keys
An ampersand in the Text of a label, a button, a menu item or a check box marks the next character as an access key. Alt plus that character presses the button or, for a label, moves the focus to the next control in the tab order:
using System;
using System.Windows.Forms;
internal sealed class Form1 : Form
{
public Form1()
{
Text = "Access keys";
var nameLabel = new Label { Text = "&Name:", AutoSize = true };
var nameBox = new TextBox();
var discount = new CheckBox { Text = "Apply a &discount", AutoSize = true };
var literal = new Label { Text = "Voss & Sons", UseMnemonic = false, AutoSize = true };
var save = new Button { Text = "&Save", UseMnemonic = true };
Controls.Add(nameLabel);
Controls.Add(nameBox);
Controls.Add(discount);
Controls.Add(literal);
Controls.Add(save);
}
}
That block is a fragment: a form with no Main, so the checker counts it and does not build it. Three details of it matter. The label's key reaches the control that follows it in the tab order, which is why the label is placed before its field in the constructor. A literal ampersand in a caption needs UseMnemonic = false, or two ampersands in a row. And a button whose caption ends in a key is pressed by Alt plus that key, while AcceptButton makes Enter press it as well.
The same character can be taken twice on one form, and Windows gives the key to the first control in the tab order; the second one never sees it. A designer form with eleven controls and four ampersands is worth a minute of checking, and the reason the labels of this course carry one only where the field is part of a data-entry flow.
The tab order that runs
The rule "Tab reaches the controls that are enabled and visible, in the order of their TabIndex" is arithmetic over a list, and it runs here:
using System;
using System.Collections.Generic;
using System.Linq;
var controls = new List<Field>
{
new("nameBox", 2, TabStop: true, Visible: true, Enabled: true),
new("saveButton", 1, TabStop: true, Visible: true, Enabled: true),
new("hintLabel", 0, TabStop: false, Visible: true, Enabled: true),
new("priceBox", 1, TabStop: true, Visible: false, Enabled: true),
new("hiddenBox", 3, TabStop: true, Visible: true, Enabled: false),
};
var order = controls
.Where(field => field.TabStop && field.Visible && field.Enabled)
.OrderBy(field => field.TabIndex)
.ThenBy(field => field.Name, StringComparer.Ordinal)
.ToList();
var text = string.Join(" -> ", order.Select(field => $"{field.TabIndex}:{field.Name}"));
Console.WriteLine($"tab order: {text}");
Console.WriteLine($"declared: {controls.Count}, reachable: {order.Count}");
Console.WriteLine($"first: {order[0].Name}");
internal sealed record Field(string Name, int TabIndex, bool TabStop, bool Visible, bool Enabled);
dotnet run
tab order: 1:saveButton -> 2:nameBox
declared: 5, reachable: 2
first: saveButton
The output is the real run. Five controls are declared and two are reachable: the label is skipped because it is not a tab stop, the price box because it is invisible, and the hidden box because it is disabled. Two controls share TabIndex = 1, which is the case the second sort key exists for: a real form resolves a duplicate by the order of the controls in the container, and the run shows the tie broken by name so that the result is stable. The first reachable control is the one that gets the focus when the form opens, which is why the first tab stop of a data-entry form is the first field and not a button.
Exercises
- Add a sixth control with TabIndex 1 and a name that sorts before saveButton, and run the program again.
- Change the order to use Descending and explain which control a user would reach first.
- Print a warning line for every duplicate TabIndex, and run it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which property carries an object of your own with a control?
Answer
Tag
Tag is an object field for an id or a row, kept by the control and read by the handler.
-
What does Enabled = false do to a control?
Answer
Greys it out, takes it out of the tab order and stops input events
A disabled control cannot be reached or used; Visible = false is the other property.
-
What does Visible = false do that Enabled = false does not?
Answer
Removes the control's space from the layout
A hidden control leaves no gap; a disabled one keeps its place.
-
What decides the tab order of the children of a GroupBox?
Answer
Their TabIndex inside the group, and the group's TabIndex among its siblings
Each container numbers its own children, so the group is one step in the form's order.
-
What does TabStop = false on a Label do?
Answer
Keeps the focus from stopping on the label
A label is not an input control, so it is skipped even though it has a TabIndex.
-
When does Focus() fail quietly?
Answer
When the control cannot take the focus, for example before the form is shown
It returns false; a dialog that needs a field focused does it in Shown.
-
What does an ampersand in a Label's Text do?
Answer
Marks an access key that sends the focus to the next control
For a button it presses the button; for a label it moves the focus.
-
How do you show a literal ampersand in a caption?
Answer
UseMnemonic = false, or two ampersands
With mnemonics off the character is drawn as written.
-
What did the run print as reachable?
Answer
2 of 5 controls
One control is not a tab stop, one is invisible and one is disabled.
-
Which control gets the focus when a form opens with no explicit choice?
Answer
The first reachable control in the tab order
The first tab stop of the form is where the caret goes, which is why it should be the first field.
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