In the last introduction to SDL2 audio and video rendering, we just showed a window that automatically disappeared after 3 seconds. How to make this window like other normal application window can be dragged, minimized, closed, and so on, this time needs SDL event processing. The event handling referred to here is commonly referred to as keyboard events, mouse events, window events, etc. SDL encapsulates these events and provides a unified API.

SDL event processing

In SDL, all events are stored in a queue, and then the data is pulled out of the queue through a loop for processing. All operations on events are operations on the queue.

Take the code SDL_Delay(3000) from the previous article; // Change the delay to 3 seconds:

while (quit) {
    SDL_WaitEvent(&event);
    switch (event.type) {
        case SDL_QUIT:// Exit the event
            SDL_Log("quit");
            quit = 0;
            break;
        default:
            SDL_Log("event type:%d", event.type); }}Copy the code

Implement a click window “X” number to close the window function.

Event rotation training mode

SDL_WaitEvent: event-driven. The process is triggered only when an event exists in the list. Otherwise, the process is blocked and the CPU is released

SDL_PollEvent: in rotation mode, data is constantly extracted from the list at regular intervals (may cause 100% CPU)

SDL_WaitEventTimeout: different from SDL_WaitEvent, when the timeout period is reached, the blocking state exits.

If we have SDL_WaitEvent, why should we have SDL_PollEvent? This is mainly due to the different scenarios used. For games that require real-time processing of events, use SDL_PollEvent; For some other cases where real time is not high, SDL_WaitEvent can be used instead.Copy the code

SDL Event type

SDL_WindowEvent: Window-related events.

SDL_KeyboardEvent: keyboard-related events.

SDL_MouseMotionEvent: events related to mouse movement.

SDL_QuitEvent: exit event.

SDL_UserEvent: user-defined event.

See the SDL Wiki for more information