Search code examples
c++sdlsdl-2

How to detect which key was pressed in SDL2 without repetitive cases?


I need to create an input box in a SDL window.

Since there is no function for that I am going to make a basic input box, but I can't find how to detect which key is pressed in SDL.

With this code below, I can print when I hit 'A' but i think making this for each character will be really repetitive. How can I detect which key is pressed?

case: SDL_KEYDOWN:
    switch (event.key.keysym.sym) {
        case SDLK_a:
            cout << "You Clicked \'A\'" << endl;
            break;
    }

Solution

  • SDL_Keysym::sym is an SDL_Keycode value. As you can see in the lookup table, these keycodes just correspond to ASCII values where possible. Checking if it's between 0x20 and 0x7f (inclusive) should be a decent way to detect that.

    You can also use SDL_GetKeyName to get the name of the key as a string.

    Note that modifiers like Shift are not taken into account. I assume that's okay because you asked for detecting key presses, not typed characters. Otherwise, SDL_TextInputEvent is probably closer to what you need.