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.

What the arguments carry

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:

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

  1. Add a binding for Escape and one for F5, and run the program.
  2. Make the table case-insensitive by lower-casing the character before the lookup, and run it again.
  3. 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.

  1. Which event reports the character a key produced?

    Answer

    KeyPress

    KeyPress carries KeyChar and fires only for keys that produce a character.

  2. Which event fires for the arrow keys?

    Answer

    KeyDown, but not KeyPress

    An arrow produces no character, so KeyPress never fires for it.

  3. What does e.Modifiers contain?

    Answer

    The modifier keys, such as Control or Shift

    KeyData combines the two; Modifiers is just the modifiers.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. What did the run print for Ctrl+x?

    Answer

    Ctrl+x -> nothing

    The lookup missed and the default was nothing.

  9. 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.

  10. 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

Banner image