Events, keyboard & mouseSDL 3.2

SDL_PollEvent

Takes the next event out of the queue, if there is one. Never waits.

Signature

bool SDL_PollEvent(SDL_Event *event);

How it works

Everything the user does (keys, mouse, closing the window, plugging a gamepad) becomes an SDL_Event in a queue. Each frame, empty the queue with while (SDL_PollEvent(&e)), then update and draw. If you stop reading events the system thinks the program froze ("not responding").

SDL_Event is a union: look at e.type first, then read the matching member: e.key for keys, e.motion and e.button for the mouse, e.wheel, e.window, e.text, e.gdevice…

Parameters

eventSDL_Event *

Where to copy the event. With NULL it only tells whether an event is waiting, without removing it.

Return value

true if an event was taken out, false if the queue is empty.

Tips & pitfalls

  • Call it from the thread that created the window (normally the main thread).

  • Key events: e.key.key is the SDL_Keycode (the symbol, layout-aware, e.g. SDLK_A), e.key.scancode the physical position (SDL_SCANCODE_A), e.key.down and e.key.repeat are bools.

Example

example.cpp
1SDL_Event e;
2while (SDL_PollEvent(&e)) {
3    switch (e.type) {
4    case SDL_EVENT_QUIT:          running = false; break;
5    case SDL_EVENT_KEY_DOWN:
6        if (e.key.key == SDLK_ESCAPE) running = false;
7        break;
8    case SDL_EVENT_MOUSE_BUTTON_DOWN:
9        click(e.button.x, e.button.y);   // floats in SDL3
10        break;
11    }
12}
Official SDL wiki