Custom controls and hit testing
A custom control is the answer when the controls of the framework cannot show the thing. There are two ways to build one, and the choice is about who owns the paint: a Control subclass draws every pixel itself, and a UserControl is a container of ordinary controls with a property and an event of its own. Both end in the same question a form ends in: what does a click mean?
A Control with its own paint
A control derived from Control is an empty window: it has a handle, it raises mouse and keyboard events, and it paints nothing until OnPaint does. The constructor turns on the styles that make the paint work:
internal sealed class RatingControl : Control
{
private int _value;
public RatingControl()
{
SetStyle(
ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint,
true);
Width = 140;
Height = 32;
AccessibleName = "Rating";
AccessibleRole = AccessibleRole.Slider;
}
[DefaultValue(0)]
public int Value
{
get => _value;
set
{
var clamped = Math.Clamp(value, 0, 5);
if (_value == clamped)
{
return;
}
_value = clamped;
Invalidate();
ValueChanged?.Invoke(this, EventArgs.Empty);
}
}
public event EventHandler? ValueChanged;
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
for (var i = 0; i < 5; i++)
{
var star = new Rectangle(4 + (i * 26), 6, 20, 20);
using var brush = new SolidBrush(i < _value ? Color.Gold : Color.LightGray);
e.Graphics.FillEllipse(brush, star);
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button != MouseButtons.Left || e.X < 4)
{
return;
}
var index = (e.X - 4) / 26;
if (index < 5)
{
Value = index + 1;
}
}
}
Four properties make it a control rather than a picture. Value clamps its input and raises ValueChanged only when the value really changed, which is the same early return the view model of lesson 055 uses. [DefaultValue(0)] tells the designer what the default is, so it does not persist a zero into every form. AccessibleRole.Slider says what a screen reader should announce for a control whose name is otherwise only a guess. And Invalidate in the setter is the link between the model and the paint: a value change is a request for a repaint, not a repaint.
The click and the paint must agree on the geometry. The paint puts a circle at 4 + i * 26 with a diameter of 20; the click divides e.X - 4 by 26, so a click anywhere in a star's slot, including the six-pixel gap after the circle, selects it. That is a decision, and a fair one for a rating: the gaps are small and a user aims at the star. A control that needed pixel accuracy would test the point against each circle's rectangle instead.
A UserControl
A UserControl is a panel with a designer of its own. It is the right base when the thing is a group of existing controls: a numeric box with a unit label, a search box with a button, a row of a form. It exposes the properties and events the form needs, and hides the rest:
internal sealed class QuantityPicker : UserControl
{
private readonly NumericUpDown _box = new() { Minimum = 1, Maximum = 99, Value = 1, Dock = DockStyle.Fill };
public QuantityPicker()
{
Width = 80;
Height = 24;
_box.ValueChanged += (sender, e) => QuantityChanged?.Invoke(this, EventArgs.Empty);
Controls.Add(_box);
}
[DefaultValue(1)]
public decimal Quantity
{
get => _box.Value;
set => _box.Value = value;
}
public event EventHandler? QuantityChanged;
}
Three details. The inner NumericUpDown is Dock.Fill, so the user control's size is the layout and the box follows it. The QuantityChanged event is raised by the inner control and re-raised with this as the sender, so the form's handler knows which picker it came from. And the control has no public NumericUpDown property: a form that could reach inside would couple itself to the implementation, and the control could not change its layout later.
The form that hosts them
The whole program: both controls, a form that uses them and a summary label. Built and not run:
using System;
using System.ComponentModel;
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 RatingControl : Control
{
private int _value;
public RatingControl()
{
SetStyle(
ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint,
true);
Width = 140;
Height = 32;
AccessibleName = "Rating";
AccessibleRole = AccessibleRole.Slider;
}
[DefaultValue(0)]
public int Value
{
get => _value;
set
{
var clamped = Math.Clamp(value, 0, 5);
if (_value == clamped)
{
return;
}
_value = clamped;
Invalidate();
ValueChanged?.Invoke(this, EventArgs.Empty);
}
}
public event EventHandler? ValueChanged;
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
for (var i = 0; i < 5; i++)
{
var star = new Rectangle(4 + (i * 26), 6, 20, 20);
using var brush = new SolidBrush(i < _value ? Color.Gold : Color.LightGray);
e.Graphics.FillEllipse(brush, star);
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button != MouseButtons.Left || e.X < 4)
{
return;
}
var index = (e.X - 4) / 26;
if (index < 5)
{
Value = index + 1;
}
}
}
internal sealed class QuantityPicker : UserControl
{
private readonly NumericUpDown _box = new() { Minimum = 1, Maximum = 99, Value = 1, Dock = DockStyle.Fill };
public QuantityPicker()
{
Width = 80;
Height = 24;
_box.ValueChanged += (sender, e) => QuantityChanged?.Invoke(this, EventArgs.Empty);
Controls.Add(_box);
}
[DefaultValue(1)]
public decimal Quantity
{
get => _box.Value;
set => _box.Value = value;
}
public event EventHandler? QuantityChanged;
}
internal sealed class Form1 : Form
{
private readonly RatingControl _rating = new() { Location = new Point(16, 16) };
private readonly QuantityPicker _quantity = new() { Location = new Point(16, 64) };
private readonly Label _summary = new() { Location = new Point(16, 100), AutoSize = true };
public Form1()
{
Text = "Custom controls";
ClientSize = new Size(360, 150);
_rating.ValueChanged += (sender, e) => UpdateSummary();
_quantity.QuantityChanged += (sender, e) => UpdateSummary();
Controls.Add(new Label { Text = "Rating:", AutoSize = true, Location = new Point(16, 0) });
Controls.Add(new Label { Text = "Quantity:", AutoSize = true, Location = new Point(140, 46) });
Controls.Add(_rating);
Controls.Add(_quantity);
Controls.Add(_summary);
UpdateSummary();
}
private void UpdateSummary() =>
_summary.Text = $"{_rating.Value} of 5, quantity {_quantity.Quantity:0}";
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The form is a participant of lesson 052's pattern without knowing it: the two controls raise events and the form decides what to show. The one detail worth noticing is the method name: Show would have hidden Control.Show() and earned a compiler warning, which the build above does not have because the method is called UpdateSummary. Naming a member after an inherited one is a real source of confusion in a control's own API.
Hit testing that runs
The click handler of a custom control is a pure function: a point in, a row and a column or nothing out. Here is that function for a grid with an origin, a cell size and bounds, and for the star row of the control above. It was built and run here:
using System;
using System.Drawing;
Console.WriteLine("hit testing a grid and a row of stars");
var grid = new CellGrid(originX: 16, originY: 40, cellWidth: 60, cellHeight: 24, columns: 5, rows: 4);
var points = new[]
{
new Point(20, 44),
new Point(100, 80),
new Point(15, 44),
new Point(200, 44),
new Point(20, 200),
};
foreach (var point in points)
{
var hit = grid.HitTest(point);
Console.WriteLine(hit is null
? $"{point}: no cell"
: $"{point}: row {hit.Value.Row}, column {hit.Value.Column}");
}
var stars = new StarRow(firstX: 4, spacing: 26, diameter: 20, count: 5);
foreach (var x in new[] { 0, 10, 28, 120, 200 })
{
var index = stars.IndexAt(x);
Console.WriteLine($"x {x}: {(index is null ? "no star" : $"{index} stars")}");
}
internal readonly record struct CellHit(int Row, int Column);
internal sealed class CellGrid
{
private readonly int _originX;
private readonly int _originY;
private readonly int _cellWidth;
private readonly int _cellHeight;
private readonly int _columns;
private readonly int _rows;
public CellGrid(int originX, int originY, int cellWidth, int cellHeight, int columns, int rows)
{
_originX = originX;
_originY = originY;
_cellWidth = cellWidth;
_cellHeight = cellHeight;
_columns = columns;
_rows = rows;
}
public CellHit? HitTest(Point point)
{
var x = point.X - _originX;
var y = point.Y - _originY;
if (x < 0 || y < 0)
{
return null;
}
var column = x / _cellWidth;
var row = y / _cellHeight;
if (column >= _columns || row >= _rows)
{
return null;
}
return new CellHit(row, column);
}
}
internal sealed class StarRow
{
private readonly int _firstX;
private readonly int _spacing;
private readonly int _diameter;
private readonly int _count;
public StarRow(int firstX, int spacing, int diameter, int count)
{
_firstX = firstX;
_spacing = spacing;
_diameter = diameter;
_count = count;
}
public int? IndexAt(int x)
{
if (x < _firstX)
{
return null;
}
var index = (x - _firstX) / _spacing;
if (index >= _count || x > _firstX + (index * _spacing) + _diameter)
{
return null;
}
return index + 1;
}
}
dotnet run
hit testing a grid and a row of stars
{X=20,Y=44}: row 0, column 0
{X=100,Y=80}: row 1, column 1
{X=15,Y=44}: no cell
{X=200,Y=44}: row 0, column 3
{X=20,Y=200}: no cell
x 0: no star
x 10: 1 stars
x 28: no star
x 120: 5 stars
x 200: no star
The output is the real run, and it names every boundary. A point four pixels inside the grid is row 0, column 0; a point one pixel left of the origin is outside, which a subtraction without the x < 0 check would report as column 0 because integer division rounds toward zero. The star at x = 28 falls in the six-pixel gap and selects nothing, and x = 120 is inside the fifth circle. Hit testing is arithmetic, and arithmetic is what runs on this machine.
The same two methods become the control's handlers in three lines: OnMouseDown calls HitTest and returns when it is null; a mouse-move that hovers calls it to decide the cursor; a tooltip handler calls it to pick the text. Keeping the arithmetic in a separate class is what lets this page test it without a window.
A custom control and accessibility
Every control has the accessibility properties of lesson 058, and a custom control starts with almost none of them set. A screen reader sees a control with no role and no name, so the four properties are not optional here:
- AccessibleName: "Rating" here. Without it the reader has nothing to say.
- AccessibleRole: Slider, so the reader announces a value that can be changed. Graphic or Pane would say the control is decoration.
- AccessibleDescription: what five stars mean, if it is not obvious from the name.
- AccessibleDefaultActionDescription: "Sets the rating", for the click.
A custom control also needs a keyboard route: arrow keys that change Value, TabStop = true and a focus rectangle. A mouse-only control is unusable for a keyboard user, and the reader cannot offer an action the control does not have. A UserControl gets some of this from its children, which is one more reason to prefer it when the control is a group of existing controls.
Exercises
- Add arrow-key handling to RatingControl and set TabStop in the constructor.
- Change the star hit test to test the circle instead of the slot, and run the geometry program with the same x values.
- Add a Unit property to QuantityPicker that appends a label, and explain what the form gains.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which base class draws every pixel itself?
Answer
Control
A UserControl is a container of existing controls.
-
Which style combination makes a custom control paint without flicker?
Answer
OptimizedDoubleBuffer, AllPaintingInWmPaint and UserPaint
The star control sets all three.
-
Why does the Value setter call Invalidate?
Answer
A value change needs a repaint, and Invalidate schedules one
The paint reads the value; the setter asks for the paint.
-
What does [DefaultValue(0)] tell the designer?
Answer
The value it may leave out of the generated code
The designer persists only values that differ from the default.
-
Which point is outside the grid in the run?
Answer
X=15, left of the origin
The subtraction gives a negative x, and the guard returns null.
-
Why does a point at x = 28 select no star?
Answer
It is in the six-pixel gap after the first circle
The circle ends at 24 and the next begins at 30.
-
What does the UserControl re-raise with this as the sender?
Answer
Its own QuantityChanged event
The form then knows which picker raised it.
-
Which accessibility role does the rating control use?
Answer
Slider
It announces a value that can be changed.
-
Why is a mouse-only custom control an accessibility bug?
Answer
A keyboard user cannot reach or change it
It needs TabStop, a focus rectangle and key handling.
-
Why is the hit test arithmetic in a separate class?
Answer
So it can be run and tested with no window
That is what lets this page run it on Linux.
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