Init, errors & main callbacksSDL 3.2

SDL_AppEvent

A function YOU write: SDL calls it once for every event (key, mouse, quit…).

Signature

SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event);

How it works

It replaces the while (SDL_PollEvent(&e)) loop: SDL polls for you and hands over each event. Look at event->type and react.

The close button arrives as SDL_EVENT_QUIT. Return SDL_APP_SUCCESS for it, and the program ends cleanly through SDL_AppQuit.

Parameters

appstatevoid *

The pointer you stored in SDL_AppInit.

eventSDL_Event *

The event. Valid only during this call.

Return value

SDL_APP_CONTINUE to keep going; SDL_APP_SUCCESS or SDL_APP_FAILURE to end the program.

Tips & pitfalls

  • Events SDL itself produces arrive between two SDL_AppIterate calls, one after another. An event YOUR worker thread pushes with SDL_PushEvent can arrive on that thread, at the same time as SDL_AppIterate: protect shared data then.

Example

example.cpp
1SDL_AppResult SDL_AppEvent(void* appstate, SDL_Event* event) {
2    auto* app = static_cast<App*>(appstate);
3    if (event->type == SDL_EVENT_QUIT) return SDL_APP_SUCCESS;
4    if (event->type == SDL_EVENT_KEY_DOWN && event->key.key == SDLK_SPACE)
5        app->paused = !app->paused;
6    return SDL_APP_CONTINUE;
7}
Official SDL wiki