Mouse events
The lessons before this one handled a click. A drag is the other half of the mouse: the button goes down in one place, the pointer moves, the button comes up somewhere else, and the control is supposed to follow it. That is three events and one property, and the property is the one everybody forgets.
A drag is three events
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
{
private readonly Panel _surface = new()
{
Location = new Point(16, 16),
Size = new Size(320, 180),
BackColor = SystemColors.Window,
BorderStyle = BorderStyle.FixedSingle,
};
private readonly Label _status = new() { Location = new Point(16, 204), AutoSize = true };
private Point _start;
private bool _dragging;
public Form1()
{
Text = "Drag to select";
ClientSize = new Size(360, 240);
_surface.MouseDown += OnDown;
_surface.MouseMove += OnMove;
_surface.MouseUp += OnUp;
Controls.Add(_surface);
Controls.Add(_status);
}
private void OnDown(object? sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
{
return;
}
_start = e.Location;
_dragging = true;
_surface.Capture = true;
_status.Text = $"from {_start.X},{_start.Y}";
}
private void OnMove(object? sender, MouseEventArgs e)
{
if (!_dragging)
{
return;
}
_status.Text = $"{_start.X},{_start.Y} to {e.X},{e.Y}";
}
private void OnUp(object? sender, MouseEventArgs e)
{
if (!_dragging)
{
return;
}
_dragging = false;
_surface.Capture = false;
_status.Text = $"released at {e.X},{e.Y}";
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. Three lines carry the lesson. e.Button != MouseButtons.Left ignores a right button, which a selection surface must decide about explicitly. _surface.Capture = true is what keeps the moves coming once the pointer leaves the panel: without it the control stops receiving MouseMove at its edge and the drag ends there. And _dragging guards the handlers, because a MouseMove arrives whenever the pointer moves over the panel, button or no button.
What MouseEventArgs carries
- Button: the button that caused the event, MouseButtons.Left, Right, Middle, XButton1 or XButton2. None for a move.
- Location, X and Y: the position in client coordinates, which is the top-left corner of the control as (0, 0). This is the coordinate a control wants for its own drawing and hit testing.
- Clicks: how many times the button has been pressed in this sequence. A double click reports 2.
- Delta: the wheel movement in units of 120, negative when the wheel turns towards the user.
Client coordinates are relative to the control, and screen coordinates are relative to the desktop. The two convert with PointToClient and PointToScreen, which is what a control needs when it shows a menu at the pointer or compares positions across controls:
using System;
using System.Drawing;
using System.Windows.Forms;
internal sealed class Form1 : Form
{
public Form1()
{
Text = "Where is the pointer";
var surface = new Panel { Dock = DockStyle.Fill, BackColor = SystemColors.Window };
surface.MouseMove += (sender, e) =>
{
var screen = surface.PointToScreen(e.Location);
var back = surface.PointToClient(screen);
Text = $"client {e.X},{e.Y} screen {screen.X},{screen.Y} back {back.X},{back.Y}";
};
Controls.Add(surface);
}
}
That block is a fragment: a form with no Main, so the checker counts it and does not build it. The round trip is the point: a point converted to the screen and back is the same point, and a context menu shown at PointToScreen(e.Location) appears under the pointer.
Capture and the pointer
The mouse belongs to the control under the pointer, not to the one that wants it. Capture = true changes that for the duration of a drag: every mouse message goes to the capturing control until the button is released, which is why a scrollbar thumb keeps following the pointer outside the bar.
- MouseEnter and MouseLeave: the pointer entered or left the control. They carry a plain EventArgs and are the right place for a hover effect.
- MouseHover: the pointer rested over the control for the system's hover time. A ToolTip uses the same idea.
- MouseWheel: the wheel turned while the control had the focus, with Delta. Scroll the control the pointer is over by handling it on that control, not on the form.
- Cursor: the pointer shape over the control, Cursors.SizeNS for a horizontal splitter or Cursors.Hand for a link.
One rule of the platform is worth knowing here: a control that is not selectable or not enabled receives no mouse events at all. A Label is not selectable by default and still gets them, because the message goes to the control under the pointer; a disabled control does not, and a form that needs a click there handles it on the parent.
A selection rectangle that runs
A drag that selects has to turn two points into one rectangle, in any direction the user dragged. That arithmetic is plain numbers, and it runs here:
using System;
var start = (X: 60, Y: 20);
var end = (X: 20, Y: 70);
var bounds = (Width: 200, Height: 100);
var box = Normalise(start, end, bounds);
Console.WriteLine($"selection: x={box.X} y={box.Y} w={box.Width} h={box.Height}");
Console.WriteLine($"empty: {box.Width == 0 || box.Height == 0}");
Console.WriteLine($"contains 40,40: {Contains(box, 40, 40)}");
Console.WriteLine($"contains 150,40: {Contains(box, 150, 40)}");
static (int X, int Y, int Width, int Height) Normalise(
(int X, int Y) first,
(int X, int Y) second,
(int Width, int Height) bounds)
{
var left = Math.Clamp(Math.Min(first.X, second.X), 0, bounds.Width);
var top = Math.Clamp(Math.Min(first.Y, second.Y), 0, bounds.Height);
var right = Math.Clamp(Math.Max(first.X, second.X), 0, bounds.Width);
var bottom = Math.Clamp(Math.Max(first.Y, second.Y), 0, bounds.Height);
return (left, top, right - left, bottom - top);
}
static bool Contains((int X, int Y, int Width, int Height) box, int x, int y) =>
x >= box.X && x < box.X + box.Width && y >= box.Y && y < box.Y + box.Height;
dotnet run
selection: x=20 y=20 w=40 h=50
empty: False
contains 40,40: True
contains 150,40: False
The output is the real run. The drag ran from 60,20 to 20,70 — up and to the left — and the rectangle is normalised to a left and a top, which is why it starts at 20,20 and not at the first point. The clamp keeps a drag that leaves the panel inside its bounds, which is the arithmetic behind Capture: the events keep coming from outside the control, and the rectangle has to stay where the control can draw it. The hit test uses < on the far edge so that two adjacent rectangles do not both contain the boundary point.
Exercises
- Add a second selection at 240,10 to 250,10 and explain why the result is empty.
- Make Normalise drop the clamp and run the program with a drag that ends outside the bounds.
- Write the two lines of a MouseWheel handler that scrolls a panel by the Delta of the event.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which event carries the button and the position of a press?
Answer
MouseDown, with MouseEventArgs
Click passes a plain EventArgs, so a handler that needs the position subscribes to MouseDown or MouseClick.
-
What are the coordinates in MouseEventArgs.Location relative to?
Answer
The client area of the control, whose top-left corner is 0,0
PointToScreen converts them when a screen position is needed.
-
What does Capture = true do?
Answer
Sends every mouse message to that control until the button is released
It is what keeps a drag going when the pointer leaves the control.
-
Why do the drag handlers need a _dragging flag?
Answer
MouseMove arrives whenever the pointer moves, button or no button
The flag is what makes a move part of a drag.
-
Which value of MouseEventArgs.Button means no button?
Answer
MouseButtons.None
A move without a button reports None.
-
What does MouseEventArgs.Delta carry?
Answer
The wheel movement in units of 120
Negative when the wheel turns towards the user.
-
Which pair converts between client and screen coordinates?
Answer
PointToClient and PointToScreen
They are methods of Control, and the round trip returns the same point.
-
What did the run print for the normalised selection?
Answer
x=20 y=20 w=40 h=50
The left and top come from the smaller coordinates of the two points.
-
Why does the hit test use < on the far edge?
Answer
So two adjacent rectangles do not both contain the boundary point
A half-open interval makes the cells of a grid a partition.
-
Which events fire when the pointer enters and leaves a control?
Answer
MouseEnter and MouseLeave
Enter and Leave are the focus events, which are different.
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