0
\$\begingroup\$

I am trying to simulate an SDL keyboard button press (using C). I have looked up the SDL info pages online but I still don't have anything that consistently works.

I have the following (removed the interrupt handling, creation of windows etc.)

while(1){
    SDL_Event user_event;
    user_event.type = SDL_SCANCODE_LEFT;

    SDL_PushEvent(&user_event);
    SDL_PumpEvents();

    const Uint8 *state = SDL_GetKeyboardState(NULL);

    if (state[SDL_SCANCODE_LEFT]) {
        printf("LEFT PRESSED");
    }
    if (state[SDL_SCANCODE_RIGHT]) {
        printf("RIGHT PRESSED");
    }
}

I never see the 'LEFT PRESSED' string printed out, although when I press the right arrow key (from keyboard) I see the respective output generated. It appears like the left key press is never being pushed on the state var.

Any help would be greatly appreciated.

\$\endgroup\$
1
\$\begingroup\$

I use SDL quite a bit but I never use the PumpEvents function. I find that SDL_PollEvent() is the best way to go for SDL input.

Check out the following code, hopefully this helps you with your problem:

bool getKeyState(const char* key)
{
    bool status = false;

    const Uint8* keyboard = SDL_GetKeyboardState(NULL);

    if (keyboard[SDL_GetScancodeFromName(key)]) {
        status = true;
        // If you want to print out the key press details
        //std::cout << "Key pressed: " << SDL_GetScancodeName(scanCode) << " (Scancode: " << scanCode << ")" << std::endl; 
}

    return status;
}

int main()
{
    bool running = true;
    SDL_Event events;

    while (running)
    {
        SDL_PollEvents(events);

        if (getKeyState("C"))
        {
            // will trigger if C is pressed, put your action here
        }
    }

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.