Understanding Keyboard State

Learn how to detect and handle keyboard input in SDL2 using both event-driven and polling methods. This lesson covers obtaining and interpreting the keyboard state array.

Ryan McCombe
Updated

In previous lessons, we introduced how we can detect and react to keyboard input through the event loop:

#include <SDL.h>
#include "Window.h"

void HandleKeyboardEvent(SDL_KeyboardEvent& E) {
  // ...
}

int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_VIDEO);
  Window GameWindow;
  SDL_Event Event;

  while (true) {
    while (SDL_PollEvent(&Event)) {
      if (Event.type == SDL_KEYDOWN)
        HandleKeyboardEvent(Event.key);
    }
  }

  SDL_Quit();
  return 0;
}

However, there is another option. At any time within our application, we can query SDL to find out which keys are currently pressed.

Getting Keyboard State

SDL maintains an array of UInt8 values to represent the state of the user's keyboard. This array has an integer for every key on the user's keyboard, and we can receive a const pointer to it using the SDL_GetKeyboardState() function.

This function receives a pointer to an integer as an argument, which it updates with the size of the array:

#include <iostream>
#include <SDL.h>
#include "Window.h"

void HandleKeyboard() {
  int Size;
  SDL_GetKeyboardState(&Size);

  std::cout << "Array Size: " << Size;
}


int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_VIDEO);
  Window GameWindow;
  SDL_Event Event;

  HandleKeyboard();

while (true) {/*...*/} SDL_Quit(); return 0; }
Array Size: 512

Note that the array's size will typically be larger than the number of keys on our keyboard, meaning not every position is assigned to a key. The main reason the size is provided is to communicate the upper bound of the array, which we may need to know if we were iterating through it, for example.

If we don't need to know the size, we can pass a nullptr:

void HandleKeyboard() {
  SDL_GetKeyboardState(nullptr);
}

Determining Which Keys are Held

Once we have the keyboard array from SDL_GetKeyboardState(), we can determine if a key is currently held down by investigating the corresponding entry within that array. The index we need for each key is the scan code of that key, which SDL provides variables for.

For example, to determine if the spacebar is currently held down, we would check the index represented by SDL_SCANCODE_SPACE:

void HandleKeyboard() {
  const Uint8* State {
    SDL_GetKeyboardState(nullptr)};
    
  State[SDL_SCANCODE_SPACE];
}

The Uint8 value at each array position is 1 if the corresponding key is pressed, and 0 otherwise. 1 is truthy, and 0 is falsy, so we can directly use these values as booleans.

Below, we check on every frame whether the spacebar is held or not:

#include <iostream>
#include <SDL.h>
#include "Window.h"

void HandleKeyboard() {
  const Uint8* State {
    SDL_GetKeyboardState(nullptr)};

  if (State[SDL_SCANCODE_SPACE]) {
    std::cout << "Space is held\n";
  } else {
    std::cout << "Space is not held\n";
  }
}


int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_VIDEO);
  Window GameWindow;
  SDL_Event Event;

  while (true) {
    while (SDL_PollEvent(&Event)) {
      // ...
    }

    HandleKeyboard();
  }

  SDL_Quit();
  return 0;
}
Space is not held
Space is not held
Space is not held
Space is held
Space is held

All the scan codes we need to index into this array are available in the SDK_keycode header file.

Keyboard State and the Event Queue

For SDL to update its keyboard state array, we must instruct it to process its event queue. In the previous examples, and in most applications, we've been doing that within our application loops.

Specifically, the continuous calls to SDL_PollEvent() prompt SDL to keep its various components up to date, including the keyboard state array:

SDL_Event Event;

while (true) {
  while (SDL_PollEvent(&Event)) {
    // React to events
    // ...
  }

  HandleKeyboard();
}

Even if we don't need to react to the events, we still need to prompt SDL to process them at the appropriate time within the application loop.

However, if we don't need to inspect the events, we can simplify our loop by using SDL_PumpEvents() instead of SDL_PollEvent():

SDL_Event Event; 

while (true) {
  SDL_PumpEvents(); 
  HandleKeyboard();
}

SDL_PumpEvents() and SDL_PollEvent() have a similar purpose, but are different in two key ways:

  • SDL_PumpEvents() processes all the outstanding events on the queue, whilst SDL_PollEvent() only handles one event per invocation. As such, we can remove the inner loop - we only need to call SDL_PumpEvents() once per frame.
  • SDL_PumpEvents() doesn't give us visibility of each individual event. As such, we can remove the argument, and delete the SDL_Event variable it was based on.

Events vs Polling

We've now seen two different approaches we can take to handle keyboard input. These designs are typically referred to as event-driven and polling:

  • Event-based designs handle input through the event loop. Our application loop detects the keyboard events we're interested in and notifies the interested objects.
  • Polling-based designs instead have those objects directly examine the keyboard state. This is referred to as polling as it generally needs to happen continuously - typically every frame

Each design has its advantages and disadvantages and, in a more complex application, both techniques tend to be used.

Event-based designs tend to be preferred for interactions that are discrete rather than continuous. Examples of discrete actions include the user pressing a key to open up a menu, or clicking on a button in the UI.

Event implementations also tend to be more performant than polling, especially when the event is infrequent. Polling every frame to detect a state that rarely happens is usually a waste of resources, and is better implemented through the event queue.

Polling designs are more appropriate for interactions that tend to be continuous. For example, movement input is often implemented by the user holding down one of several designated keys.

In that scenario, having the movement system implement frame-by-frame polling to determine which movement keys are held down is typically cleaner than reacting to keydown and keyup actions coming from the event queue.

Summary

In this lesson, we explored how to handle keyboard input in SDL2 using both event-driven and polling methods. We learned how to obtain and interpret the keyboard state array to detect key presses.

  • SDL maintains an array to represent the keyboard state.
  • The SDL_GetKeyboardState() function provides access to this array.
  • C-style arrays are used, which are primitive and require manual size handling.
  • We can check if a key is pressed by indexing the array with the key's scan code.
  • The keyboard state array is updated when SDL processes its event queue.
  • Event-driven and polling methods have different use cases and can be used together in complex applications.
Next Lesson
Lesson 49 of 129

Window Configuration

Explore window creation, configuration, and event handling using SDL's windowing system

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

SDL_PollEvent() vs SDL_PumpEvents()
What is the difference between SDL_PollEvent() and SDL_PumpEvents()?
Handling Multiple Key Presses
How can I handle multiple key presses simultaneously using SDL_GetKeyboardState()?
Advantages of Event-driven Input
What are the advantages of using event-driven input handling over polling?
Modifying the Keyboard State Array
Can I modify the keyboard state array directly?
Determining a Key's Scan Code
How do I determine the scan code for a specific key?
Keyboard State When Application Loses Focus
What happens to the keyboard state array when my application loses focus?
Handling Key Releases with Polling
How can I handle key releases using the polling method?
Debouncing Key Presses in SDL
What is the best way to debounce key presses in SDL?
Detecting Multiple Keys in a Specific Order
How can I detect if multiple keys are held down in a specific order?
Polling for Continuous Interactions
What are some examples of continuous interactions best handled by polling?
Implications of Using SDL_PumpEvents() without Processing Events
What are the implications of using SDL_PumpEvents() without processing the events?
Or Ask your Own Question
Purchase the course to ask your own questions