Key events
A WinForms control receives the keyboard as three events, and the difference between them is the difference between a key and a character: KeyDown reports the physical key, KeyPress reports the character it produced, and KeyUp reports the release. A program that binds commands handles the first; a program that filters input handles the second.
Three keyboard 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 Label _log = new() { Dock = DockStyle.Fill };
public Form1()
{
Text = "Keys";
ClientSize = new Size(420, 200);
var box = new TextBox { Location = new Point(16, 16), Width = 300 };
box.KeyDown += (sender, e) => Append($"KeyDown {e.KeyCode} {e.Modifiers}");
box.KeyPress += (sender, e) => Append($"KeyPress '{e.KeyChar}' ({(int)e.KeyChar})");
box.KeyUp += (sender, e) => Append($"KeyUp {e.KeyCode}");
Controls.Add(box);
Controls.Add(_log);
}
private void Append(string line)
{
_log.Text = _log.Text.Length == 0 ? line : _log.Text + Environment.NewLine + line;
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. Typing A raises KeyDown with Keys.A, then KeyPress with the character 'A', then KeyUp. Typing Shift+A is the same three events with Keys.A | Keys.Shift in KeyDown and the capital in KeyPress, which is the whole point of having both: the key is one, the character is the other.
- KeyDown and KeyUp: every key, including Shift, Ctrl, Alt, the arrows, Tab and Escape. The argument is a KeyEventArgs.
- KeyPress: only the keys that produce a character. The argument is a KeyPressEventArgs with KeyChar, and an arrow or a function key produces none.
- PreviewKeyDown: the event before KeyDown, and the one that can mark a key as an input key so that a control which swallows it passes it on. It matters for the arrows and Tab in a custom control.
What the arguments carry
- KeyCode: the key as a Keys value, Keys.A or Keys.F5. This is the one a command table is keyed by.
- KeyData: the key together with the modifiers, so Keys.Control | Keys.S.
- Modifiers: just the modifiers, Keys.Shift or Keys.Control | Keys.Alt. Reading it is cleaner than masking KeyData.
- Handled and SuppressKeyPress: the two ways to stop a key. Handled = true marks the event as done; SuppressKeyPress = true also stops KeyPress and the control's own handling, which is what a filter in a text box needs.
- KeyPressEventArgs.KeyChar and Handled: the character and its own stop. '' is Backspace, '\r' is Enter and (char)27 is Escape, which is why a filter compares characters and not keys.
Stopping a key
A field that accepts digits only can refuse the character before it appears, which is cheaper than cleaning the text afterwards:
using System;
using System.Drawing;
using System.Windows.Forms;
internal sealed class DigitBox : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!char.IsAsciiDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
base.OnKeyPress(e);
}
}
That block is a fragment: a class on its own, so the checker counts it and does not build it. char.IsControl lets Backspace and the other editing keys through, because a field that refuses them cannot be corrected. The Handled flag stops the control from inserting the character; a paste never reaches KeyPress, which is why the lesson about the text box cleans up in TextChanged as well.
KeyPreview and the keys a control keeps
Some keys never reach the control's KeyDown because the control uses them itself: Tab moves the focus, Enter presses the default button, the arrows move a caret or a selection, Escape closes a dialog. Two properties decide what a form sees:
- Form.KeyPreview = true: the form's KeyDown, KeyPress and KeyUp run before the focused control's, and the form may handle the key and stop it there. It is how one handler implements F1, Escape and a function-key command for the whole window.
- AcceptsTab and AcceptsReturn on a multi-line TextBox or RichTextBox let the control keep Tab and Enter instead of passing them to the form.
- ProcessCmdKey(ref Message, Keys) on a form or a control: the override that sees a command key before any of the events, and the one place where a shortcut can be handled for a control that never gets the event.
A dialog with AcceptButton and CancelButton has already claimed Enter and Escape. A form that wants Escape for something else meets that first, which is the usual surprise of the first modal dialog with a shortcut.
A key table that runs
The command a key runs is a lookup, and a lookup is the part of a shortcut system that can be tested without a keyboard. This program keeps a table of key and modifier to command and prints what five presses do, and it runs here:
using System;
using System.Collections.Generic;
var bindings = new Dictionary<(char Key, bool Control), string>
{
[('s', true)] = "save",
[('o', true)] = "open",
[(',', true)] = "settings",
[(',', false)] = "comma",
};
foreach (var press in new[] { ('s', true), ('s', false), (',', true), (',', false), ('x', true) })
{
var action = bindings.TryGetValue(press, out var name) ? name : "nothing";
var prefix = press.Item2 ? "Ctrl+" : string.Empty;
Console.WriteLine($"{prefix}{press.Item1} -> {action}");
}
Console.WriteLine($"bindings: {bindings.Count}");
dotnet run
Ctrl+s -> save
s -> nothing
Ctrl+, -> settings
, -> comma
Ctrl+x -> nothing
bindings: 4
The output is the real run. The table is keyed by the character and the modifier, so Ctrl+s and a plain s are different commands and an unbound Ctrl+x is nothing rather than an error. In a form the character comes from KeyPress and the modifier from Control.ModifierKeys, or the key and its modifiers come from KeyDown as e.KeyCode and e.Modifiers; the table is the same either way, which is why it is worth writing once and testing here.
Exercises
- Add a binding for Escape and one for F5, and run the program.
- Make the table case-insensitive by lower-casing the character before the lookup, and run it again.
- Explain from the documentation why SuppressKeyPress stops KeyPress and Handled does not always.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which event reports the character a key produced?
Answer
KeyPress
KeyPress carries KeyChar and fires only for keys that produce a character.
-
Which event fires for the arrow keys?
Answer
KeyDown, but not KeyPress
An arrow produces no character, so KeyPress never fires for it.
-
What does e.Modifiers contain?
Answer
The modifier keys, such as Control or Shift
KeyData combines the two; Modifiers is just the modifiers.
-
What does SuppressKeyPress do that Handled does not always?
Answer
It also stops KeyPress and the control's own handling
It is the stronger stop, and the one a text-box filter needs.
-
What does Form.KeyPreview = true do?
Answer
Lets the form see the key events before the focused control
It is how one handler implements F1 or Escape for the whole window.
-
Why does a digit filter accept control characters?
Answer
Backspace and the other editing keys must reach the control
A field that refuses them cannot be corrected.
-
Why does a paste bypass a KeyPress filter?
Answer
A paste changes the text without a key press per character
That is why the text box lesson cleans up in TextChanged too.
-
What did the run print for Ctrl+x?
Answer
Ctrl+x -> nothing
The lookup missed and the default was nothing.
-
Which method sees a command key before any of the events?
Answer
ProcessCmdKey
It is the override for a shortcut on a control that never gets the event.
-
Which two keys has a dialog already claimed with AcceptButton and CancelButton?
Answer
Enter and Escape
A form that wants them for something else meets that first.
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