Creating a Window

Handling Keyboard Input in SDL

How can I handle keyboard inputs in an SDL application?

Abstract art representing computer programming

This is the answer to the question. Handling keyboard input in SDL is straightforward using the SDL event system. You need to check for SDL_KEYDOWN and SDL_KEYUP events in your event loop. Here's a simple example that reacts to keyboard inputs:

#include <SDL.h>

int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_VIDEO);
  SDL_Window* window = SDL_CreateWindow(
    "Keyboard Input Window",
    SDL_WINDOWPOS_UNDEFINED,
    SDL_WINDOWPOS_UNDEFINED,
    640, 480, 0
  );
  SDL_Event event;
  bool running = true;

  while (running) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) {
        running = false;
      } else if (event.type == SDL_KEYDOWN) {
        switch (event.key.keysym.sym) {
          case SDLK_ESCAPE:
            running = false;
            break;
            // Handle other key presses here
        }
      }
    }
  }

  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}

This code initializes an SDL window and processes keyboard input to close the window when the Escape key is pressed.

Answers to questions are automatically generated and may not have been reviewed.

3D art representing computer programming
Part of the course:

Building Minesweeper with C++ and SDL2

Apply what we learned to build an interactive, portfolio-ready capstone project using C++ and the SDL2 library

Free, unlimited access

This course includes:

  • 37 Lessons
  • 100+ Code Samples
  • 92% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved