Margin, padding, DPI and fonts
The last lesson of the layout part is about the numbers that make a layout wrong on a machine that is not yours. Margin and Padding decide the gaps, the DPI mode decides whether Windows scales the form or tells it the real resolution, and the font decides the size of every text the form draws. None of them is visible in a screenshot of the developer's machine.
Margin and Padding
The two properties look alike and sit on opposite sides of the control's border:
- Margin: the space outside the control, which the parent leaves empty. It is read by a layout panel and by AutoSize of a container; a control positioned by Location simply ignores it.
- Padding: the space inside the control, between its border and its children or its text. A TextBox with padding draws its text further in; a Panel with padding holds its children away from its edges.
- The default is three pixels of margin and no padding. A FlowLayoutPanel with children at Margin = new Padding(4) has four pixels between them, which is the gap the eye reads as a row of buttons.
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 = "Gaps";
ClientSize = new Size(420, 200);
var frame = new Panel
{
Dock = DockStyle.Fill,
Padding = new Padding(16),
BorderStyle = BorderStyle.FixedSingle,
};
var caption = new Label
{
Text = "Inside the frame",
Dock = DockStyle.Top,
Padding = new Padding(6),
BackColor = SystemColors.ControlLight,
};
var field = new TextBox
{
Dock = DockStyle.Top,
Margin = new Padding(0, 8, 0, 0),
};
frame.Controls.Add(field);
frame.Controls.Add(caption);
Controls.Add(frame);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The panel's sixteen pixels of padding hold both children away from its frame; the label's six pixels of padding put its background colour around its text; the text box's margin is not used at all, because a docked child takes the whole edge it was given. That last line is the one worth remembering: Margin belongs to the parent's layout, and a docked child has no gap of its own.
AutoScaleMode
A form written at 96 DPI has to look right on a 144 DPI screen. WinForms answers with automatic scaling, which multiplies the sizes of the controls and the form by a factor computed from a reference size:
- AutoScaleMode.Font: the default. The scale factor comes from the ratio of the current font's height to the height recorded in AutoScaleDimensions. This is the mode that makes a form written with the default font look right on a machine whose system font is larger.
- AutoScaleMode.Dpi: the factor comes from the DPI, 96 against the current value. It is right when the form must not follow the user's font setting.
- AutoScaleMode.None: nothing is scaled. A form that sets it is responsible for every size itself, and it looks broken on a high-DPI screen.
The designer writes AutoScaleDimensions = new SizeF(7F, 15F) and AutoScaleMode = AutoScaleMode.Font into InitializeComponent, which is what those two lines are for: the pair records the font the layout was drawn with. A form written by hand keeps the same pair, and a form whose controls are all anchored or docked does not depend on either.
DPI and the high-DPI modes
Above automatic scaling sits the question of how Windows reports the resolution at all. The answer is the application's DPI awareness mode, which the project sets and ApplicationConfiguration.Initialize() applies:
- HighDpiMode.SystemAware: the default of a .NET WinForms project. Windows scales the whole window by the factor of the primary monitor, which is crisp on one screen and blurry on a laptop whose screens differ.
- HighDpiMode.PerMonitorV2: the form is told the DPI of the monitor it is on, and the layout is scaled again when the window moves to another monitor. This is the mode a new application should set, in the project file with ApplicationHighDpiMode, and it is the one lesson 003 writes out.
- HighDpiMode.DpiUnaware and HighDpiMode.DpiUnawareGdiScaled: the application is not told, and Windows stretches its window. A form from 2005 runs in this mode and looks soft on a modern screen.
Control.DeviceDpi reports the resolution of the monitor a control is on, and Control.DeviceDpiChanged fires when the window moves to a monitor with another one. A control that draws its own content reads DeviceDpi and scales what it draws, because nothing else will scale a Graphics operation for it.
Points, pixels and fonts
A font size is in points, and a point is a physical unit: one seventy-second of an inch. A pixel is not, which is why the two do not convert with a constant. At 96 DPI one point is 1.333 pixels; at 192 DPI it is 2.667. new Font("Segoe UI", 9F) is a nine-point font, and the pixels it occupies depend on the screen.
The practical rule that follows: never set a control's size from a count of characters. AutoSize = true on a label, AutoSize = true on a button and a layout panel with an AutoSize column give a size that is right for the font the machine actually has. A hard-coded Width = 120 is right for one font at one DPI.
The scaling arithmetic that runs
The conversion between DPI values, pixels and points is arithmetic, and it runs here:
using System;
foreach (var dpi in new[] { 96, 120, 144, 192 })
{
var scale = dpi / 96.0;
var width = (int)Math.Round(120 * scale);
var points = 9.0;
Console.WriteLine($"dpi {dpi,3} ({scale:0.00}x): 120 px -> {width} px, 9 pt -> {points * dpi / 72:0.0} px");
}
Console.WriteLine($"one point at 96 dpi: {96 / 72.0:0.000} px");
dotnet run
dpi 96 (1.00x): 120 px -> 120 px, 9 pt -> 12.0 px
dpi 120 (1.25x): 120 px -> 150 px, 9 pt -> 15.0 px
dpi 144 (1.50x): 120 px -> 180 px, 9 pt -> 18.0 px
dpi 192 (2.00x): 120 px -> 240 px, 9 pt -> 24.0 px
one point at 96 dpi: 1.333 px
The output is the real run. The first column is the scale factor an AutoScaleMode.Dpi form applies to a 120-pixel control; the second is the pixel height of nine-point text, and it is the reason a hard-coded row height of 20 pixels holds one line on a 96 DPI screen and cuts it on a 192 DPI one. A layout that uses AutoSize, Anchor and Dock needs neither column, which is the argument for the whole part of the course that ends here.
Exercises
- Add a row for 168 DPI and run the program.
- Print the pixel height of a ten-point font at each DPI, and compare it with 9 point.
- Explain from the documentation what PerMonitorV2 changes when a window is dragged to another monitor.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which property is the space outside a control?
Answer
Margin
Padding is inside the control's border, and the parent reads Margin.
-
Which layout rule ignores a child's Margin?
Answer
Docking
A docked child fills the edge it was given; a flow layout uses the margin.
-
What is the default AutoScaleMode of a WinForms form?
Answer
Font
The factor comes from the font height against AutoScaleDimensions.
-
What is AutoScaleDimensions for?
Answer
It records the font size the layout was drawn with
The scale factor is the ratio of the current font height to the recorded one.
-
Which high-DPI mode follows the monitor the window is on?
Answer
PerMonitorV2
SystemAware scales by the primary monitor only, which blurs on a mixed setup.
-
Which property reports the DPI of the monitor a control is on?
Answer
DeviceDpi
DeviceDpiChanged fires when the window moves to another monitor.
-
How many pixels is one point at 96 DPI?
Answer
1.333
A point is 1/72 inch, and the run printed the value.
-
What did the run print for 120 pixels at 144 DPI?
Answer
180 px
The scale is 144/96 = 1.5, and 120 × 1.5 is 180.
-
Why is a hard-coded Width = 120 a layout bug on another machine?
Answer
The font and the DPI decide how much space the text needs
AutoSize and layout panels size from the content instead.
-
What does AutoScaleMode.None do?
Answer
Scales nothing, so the form keeps its pixel sizes
The form is then responsible for every size, and it looks broken at high DPI.
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