keyboard input
key detection
programming
user input
coding tutorial

How to detect the currently pressed key?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Detecting the “currently pressed key” depends entirely on the platform and event model you are using. A web app, a desktop GUI, a game engine, and a console program all expose keyboard input differently. The core distinction is between event-driven detection, where you react to keydown and keyup events, and polling-based detection, where you ask the system each frame whether a key is currently held.

Web: Track keydown and keyup

In browser JavaScript, the normal approach is to listen for keyboard events and maintain a set of currently pressed keys.

html
1<!DOCTYPE html>
2<html>
3  <body>
4    <script>
5      const pressedKeys = new Set();
6
7      window.addEventListener("keydown", (event) => {
8        pressedKeys.add(event.key);
9        console.log("down:", event.key, [...pressedKeys]);
10      });
11
12      window.addEventListener("keyup", (event) => {
13        pressedKeys.delete(event.key);
14        console.log("up:", event.key, [...pressedKeys]);
15      });
16    </script>
17  </body>
18</html>

This lets you answer both:

  • what key was just pressed
  • which keys are currently held down

That second question is what many people really mean by “currently pressed key.”

Why keydown Alone Is Not Enough

If you only listen for keydown, you learn when a key press starts, but not when it ends. Without keyup, you cannot maintain accurate current state.

That matters for:

  • movement controls
  • multi-key shortcuts
  • games
  • accessibility interactions

Current key state is usually modeled as a set or map updated by both events.

C# Desktop Example

In a WinForms-style application, key events can be handled on the form.

csharp
1using System;
2using System.Collections.Generic;
3using System.Windows.Forms;
4
5public class MainForm : Form
6{
7    private readonly HashSet<Keys> pressedKeys = new();
8
9    public MainForm()
10    {
11        this.KeyPreview = true;
12        this.KeyDown += OnKeyDown;
13        this.KeyUp += OnKeyUp;
14    }
15
16    private void OnKeyDown(object? sender, KeyEventArgs e)
17    {
18        pressedKeys.Add(e.KeyCode);
19        Console.WriteLine($"Down: {e.KeyCode}");
20    }
21
22    private void OnKeyUp(object? sender, KeyEventArgs e)
23    {
24        pressedKeys.Remove(e.KeyCode);
25        Console.WriteLine($"Up: {e.KeyCode}");
26    }
27}

Again, the pattern is the same: track keydown and keyup together.

Games Often Use Polling

Game loops often poll current input state every frame instead of relying purely on discrete UI events. In those environments, the engine usually provides an API for “is this key currently held.”

For example, in many engines the shape is conceptually:

text
if key_is_down("Left"):
    move_player()

This is different from event callbacks because the main question is continuous current state, not just transitions.

Distinguish key, code, and Platform Scancodes

On the web, event.key represents the meaning of the key, while event.code represents the physical key position. That distinction matters for international keyboards.

Example:

javascript
1window.addEventListener("keydown", (event) => {
2  console.log("key:", event.key);
3  console.log("code:", event.code);
4});

If you want logical text behavior, prefer key. If you want fixed control bindings such as “physical W key,” code may be the better signal.

Repeated Keydown Events

Many platforms fire repeated keydown events while a key is held. If you only care about pressed-state membership, a set handles that cleanly because adding the same key twice changes nothing.

For example:

javascript
pressedKeys.add(event.key);

Repeated down events do not duplicate entries.

That is another reason a set is a good representation for current pressed keys.

Focus Matters

Keyboard events usually go to the focused window or focused control. If key detection “stops working,” the issue may not be your handler at all. It may be that:

  • the browser tab is unfocused
  • the form is not active
  • another control consumed the event
  • the OS intercepted the shortcut

Input debugging is often as much about focus and event routing as it is about raw key codes.

Accessibility and Reserved Shortcuts

Not every key combination is safe to capture. Browsers, operating systems, and accessibility tools reserve many combinations. If you are designing shortcuts, be careful not to interfere with expected user behavior or platform-level conventions.

The fact that a key event can be detected does not mean it should always be consumed.

Common Pitfalls

The biggest mistake is trying to infer current pressed-state from keydown alone without tracking keyup. Another is ignoring focus and assuming the application always receives keyboard events. Developers also often confuse logical key identity with physical key identity, especially on international keyboard layouts. Finally, repeated keydown events can cause noisy behavior if you do not use a stable pressed-key state structure.

Summary

  • Key detection is platform-specific, but the core model is event-driven tracking or polling.
  • To know which keys are currently held, track both keydown and keyup.
  • Use a set or similar state container to represent currently pressed keys.
  • Be aware of focus, repeated keydown events, and reserved shortcuts.
  • Distinguish logical key values from physical key positions when the platform exposes both.

Course illustration
Course illustration

All Rights Reserved.