Anchor and Dock
A WinForms form is resized by the user, and every control on it has to decide what to do about that. Two properties answer the question. Anchor keeps a control a fixed distance from the edges of its parent, and Dock makes it fill an edge or the whole client area. Almost every layout in the rest of the course is built from these two plus a container.
Anchor
Anchor is a set of flags: Top, Bottom, Left, Right, or None. Each flag means "keep the distance to that edge", and the default is Top | Left, which pins a control to the top-left corner and leaves its size alone.
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 = "Anchored fields";
ClientSize = new Size(480, 200);
MinimumSize = new Size(360, 120);
var nameBox = new TextBox
{
Location = new Point(16, 16),
Width = 448,
Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top,
};
var notes = new TextBox
{
Location = new Point(16, 52),
Size = new Size(448, 100),
Multiline = true,
Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom,
};
var close = new Button
{
Text = "Close",
Anchor = AnchorStyles.Bottom | AnchorStyles.Right,
};
close.Location = new Point(ClientSize.Width - close.Width - 16, ClientSize.Height - close.Height - 16);
Controls.Add(nameBox);
Controls.Add(notes);
Controls.Add(close);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The name box keeps 16 pixels on the left and on the right and grows with the form; the notes box does the same and also keeps 16 pixels at the bottom, so it grows in both directions; the Close button keeps its distance from the bottom-right corner, so it travels with the corner. One detail is a trap: the button's Location is computed from ClientSize at that moment, and Anchor then keeps the margins it had. A control anchored before it has its final size keeps the wrong margin, which is why the designer writes Location from the size it has just set.
The three combinations worth memorising: Left | Right stretches horizontally, Top | Bottom stretches vertically, and all four resize with the window in both directions. AnchorStyles.None is the opposite of a layout: the control keeps the position and the size the layout first gave it, and a wider window only adds empty space around it.
Dock
Dock makes a control take a whole edge of its parent and the full extent of that edge:
- DockStyle.Top: a header or a menu bar. It takes the width of the parent and the height it has.
- DockStyle.Bottom: a status bar or a row of buttons.
- DockStyle.Left and DockStyle.Right: a navigation pane or a details panel. They take the full height that is left.
- DockStyle.Fill: everything that is left after the other docked controls have taken their edges.
- DockStyle.None: the default, which leaves Anchor in charge.
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 = "Docked";
ClientSize = new Size(480, 320);
var menu = new MenuStrip();
menu.Items.Add(new ToolStripMenuItem("&File"));
var toolbar = new ToolStrip { Dock = DockStyle.Top };
toolbar.Items.Add(new ToolStripButton("Save"));
var status = new StatusStrip();
status.Items.Add(new ToolStripStatusLabel("Ready"));
var editor = new TextBox
{
Multiline = true,
Dock = DockStyle.Fill,
ScrollBars = ScrollBars.Vertical,
};
var side = new Panel { Dock = DockStyle.Right, Width = 160, BorderStyle = BorderStyle.FixedSingle };
Controls.Add(editor);
Controls.Add(side);
Controls.Add(toolbar);
Controls.Add(menu);
Controls.Add(status);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. MenuStrip docks itself to the top and StatusStrip to the bottom by default, which is why they carry no Dock line. The editor fills what is left after the menu, the toolbar, the side panel and the status bar have taken their edges, and it does so however the window is resized.
The order that matters
Two controls docked to the same edge cannot both have it, and the one that is laid out first takes its space. WinForms applies the docked controls in an order taken from the z-order of the parent's Controls collection, and Controls.Add, BringToFront and SendToBack all change that order. The practical rule is: when a docked layout is wrong, do not move the Dock lines, change the order of the Controls.Add calls or send one control to the back.
In the listing above the editor is added first and the side panel after it, and the panel takes its 160 pixels from the right before the editor fills the rest. Added in the other order, the editor would take the whole width and the panel would sit on top of it. The designer's Document Outline lists the controls in this order, which is why the outline is the first place to look at a layout that does not fit.
A docked child takes its space from the parent's client area, so the gap around it comes from the parent's Padding: a Panel with Padding = new Padding(8) holds its docked child eight pixels from every edge. The child's own Margin is not used by a docked layout, which is a difference between Margin and Padding that lesson 029 takes apart.
The arithmetic that runs
Anchoring is arithmetic on four numbers, and the horizontal half of it runs here. The child keeps 16 pixels on the sides its anchor names, and the parent grows from 400 to 600 pixels wide:
using System;
var oldWidth = 400;
var newWidth = 600;
foreach (var anchor in new[] { "None", "Left", "Right", "Left, Right" })
{
Console.WriteLine($"{anchor,-12} {Describe(anchor, oldWidth, newWidth)}");
}
Console.WriteLine($"parent: {oldWidth} -> {newWidth}");
static string Describe(string anchor, int oldWidth, int newWidth)
{
const int left = 16;
const int right = 16;
var width = oldWidth - left - right;
return anchor switch
{
"Left" => $"x={left} width={width} (right margin {newWidth - left - width})",
"Right" => $"x={newWidth - right - width} width={width}",
"Left, Right" => $"x={left} width={newWidth - left - right}",
_ => $"x={left} width={width}",
};
}
dotnet run
None x=16 width=368
Left x=16 width=368 (right margin 216)
Right x=216 width=368
Left, Right x=16 width=568
parent: 400 -> 600
The output is the real run, and it is the whole rule in four lines. Without an anchor the control keeps its position and its width, and the gap on the right grows from 16 to 216. Left is the same result and says what it keeps. Right keeps the gap on the right and lets the gap on the left grow. Left, Right keeps both gaps and gives the extra 200 pixels to the control, which is the one a field that must span the form uses.
Exercises
- Add a fourth row to the run for Top, Bottom and all four flags, and explain each width.
- Anchor a control to Left and Bottom, and work out where it goes when the parent grows in both directions.
- Describe what happens to a Dock = Fill control when it is added before and after a Dock = Right panel.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the default value of Anchor?
Answer
Top | Left
A control is pinned to the top-left corner and keeps its size unless the anchor says otherwise.
-
What does Anchor = Left | Right do when the form is widened?
Answer
Keeps both side margins and stretches the control
Each named side keeps its distance, so the extra width goes into the control.
-
What does Dock = Fill do?
Answer
Takes all the space the other docked controls leave
Fill is the remainder after the edges have been taken.
-
Which control docks to the top of a form by default?
Answer
MenuStrip
MenuStrip docks Top and StatusStrip docks Bottom without a line of code.
-
What decides which of two controls docked to the same edge gets the space?
Answer
The order they are laid out in, taken from the z-order of the collection
Controls.Add, BringToFront and SendToBack change that order.
-
What does Padding on a Panel do for its docked child?
Answer
Holds the child away from the panel's edges
Padding belongs to the parent; the child's own Padding does not affect its Dock.
-
What did the run print for Anchor = Right when the parent grew from 400 to 600?
Answer
x=216 width=368
The right margin of 16 was kept, so the left margin grew by 200.
-
Which anchor grows a control in both directions?
Answer
Top | Bottom | Left | Right
All four sides keep their distance, so both dimensions stretch.
-
Why is a Dock = Fill control usually added before the edge controls?
Answer
So the edges take their space first and Fill gets the rest
The layout order decides, and the fill is the remainder.
-
What does AnchorStyles.None do on a resize?
Answer
Leaves the control at its position and size
No side is kept, so nothing moves and nothing stretches.
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