[Prev] Table Of Contents [Next]

Using the Simple DirectMedia Layer API

Events

  • Waiting for events

Wait for events using the SDL_WaitEvent() function.

Tip:
SDL has international keyboard support, translating key events and placing the UNICODE equivalents into event.key.keysym.unicode. Since this has some processing overhead involved, it must be enabled using SDL_EnableUNICODE().
Example:
{
    SDL_Event event;

    SDL_WaitEvent(&event);

    switch (event.type) {
        case SDL_KEYDOWN:
            printf("The %s key was pressed!\n",
                   SDL_GetKeyName(event.key.keysym.sym));
            break;
        case SDL_QUIT:
            exit(0);
    }
}
  • Polling for events

Poll for events using the SDL_PollEvent() function.

Tip:
You can peek at events in the event queue without removing them by passing the SDL_PEEKEVENT action to SDL_PeepEvents().
Example:
{
    SDL_Event event;

    while ( SDL_PollEvent(&event) ) {
        switch (event.type) {
            case SDL_MOUSEMOTION:
                printf("Mouse moved by %d,%d to (%d,%d)\n", 
                       event.motion.xrel, event.motion.yrel,
                       event.motion.x, event.motion.y);
                break;
            case SDL_MOUSEBUTTONDOWN:
                printf("Mouse button %d pressed at (%d,%d)\n",
                       event.button.button, event.button.x, event.button.y);
                break;
            case SDL_QUIT:
                exit(0);
        }
    }
}
  • Polling event state

In addition to handling events directly, each type of event has a function which allows you to check the application event state. If you use this exclusively, you should ignore all events with the SDL_EventState() function, and call SDL_PumpEvents() periodically to update the application event state.

Tip:
You can hide or show the system mouse cursor using SDL_ShowCursor().
Example:
{
    SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
}

void CheckMouseHover(void)
{
    int mouse_x, mouse_y;

    SDL_PumpEvents();

    SDL_GetMouseState(&mouse_x, &mouse_y);
    if ( (mouse_x < 32) && (mouse_y < 32) ) {
        printf("Mouse in upper left hand corner!\n");
    }
}

[Prev] Table Of Contents [Next]