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\$

2 Answers 2

1
\$\begingroup\$

I believe you are constructing your SDL_Event incorrectly.

SDL_Event is a union, with the type field (SDL_EventType) used for determining what fields are actually in use. For keyboard events, use the SDL_KEYDOWN event type, and the key field (SDL_KeyboardEvent) for the keyboard specific data.

So the following should work:

SDL_Event e;
e.type = SDL_KEYDOWN;
e.key.type = SDL_KEYDOWN;
e.key.timestamp = 0;
e.key.windowID = 0;
e.key.state = SDL_PRESSED;
e.key.repeat = 0;
e.key.keysym.scancode = SDL_SCANCODE_LEFT;
e.key.keysym.sym = SDLK_LEFT;
e.key.keysym.mod = KMOD_NONE;

To be certain, you can use a debugger to capture what SDL itself does on keypress, so you can simulate this keypress in your custom event.

\$\endgroup\$
0
\$\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\$
1
  • \$\begingroup\$ While SDL_PollEvents is indeed what most people should use, it doesn't answer the OP's question of how to push custom events \$\endgroup\$ Commented Aug 22, 2022 at 4:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .