Search code examples
inputsdlsdl-2

Keyboard input for a text editor


I'm making a text editor that uses OpenGL through SDL2 to render. I'm using SDL_K switch statements to get the keyboard input:

if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE) {
    should_run = 0;
    break;
}
else if (event.type == SDL_KEYDOWN)
{
    switch (event.key.keysym.sym)
    {
        case SDLK_a:
        add_character(&test_element, 'a');
        break;

        case SDLK_b:
        add_character(&test_element, 'b');
        break;

        case SDLK_c:
        add_character(&test_element, 'c');
        break;

        case SDLK_d:
        add_character(&test_element, 'd');
        break;

        case SDLK_LEFT:
        move_cursor(&test_element, -1);
        break;

        case SDLK_RIGHT:
        move_cursor(&test_element, 1);
        break;

    }
}

For the whole keyboard, I will have two write a lot of switch cases. Is there a better way to do this?


Solution

  • Yes, there's a better way. Use the SDL_TextInputEvent, which will give you the UTF-8 representation of whatever the user is typing.