-4

I've setup 2 functions to simulate keyboard button presses

void KeyboardButtonDown(DWORD a)
{
    INPUT Input = { 0 };
    // Set up a generic keyboard event.
    Input.type    = INPUT_KEYBOARD;
    Input.ki.wVk  = a; 
    SendInput(1, &Input, sizeof(INPUT));
}

void KeyboardButtonUp(DWORD a)
{
    INPUT Input = { 0 };
    Input.type        = INPUT_KEYBOARD;
    Input.ki.dwFlags  = KEYEVENTF_KEYUP;
    Input.ki.wVk      = a;
    SendInput(1, &Input, sizeof(INPUT));
}

It works in most cases, however it fails in some apps when simulating arrow keys, as a simple exampe

KeyboardButtonDown(VK_LEFT);
Sleep(50);
KeyboardButtonUp(VK_LEFT);
Sleep(50);

It works in notepad but when playing a game it does nothing. I've mapped the controls in game to use other keys instead and it then works fine.

What am I doing wrong here?

Swordfish
  • 12,971
  • 3
  • 21
  • 43
linjoehan
  • 103
  • 1
  • 5
  • 1
    This question gets asked many times each week. Try searching for all the other times it has been asked. – David Heffernan Nov 14 '18 at 21:33
  • Possible duplicate of [Simulating Keyboard with SendInput API in DirectInput applications](https://stackoverflow.com/questions/3644881/simulating-keyboard-with-sendinput-api-in-directinput-applications) – zett42 Nov 14 '18 at 22:53
  • Games have a simple way to protect themselves against multi-player cheats, they use raw input. The only way to fool them is to inject keyboard input at the driver level, that is not a technique that the default keyboard driver puts up with. Replacing it has not been accomplished often. – Hans Passant Nov 14 '18 at 23:34

1 Answers1

2

If the receiving application uses Direct Input you have to send scan codes instead of virtual key codes.

Swordfish
  • 12,971
  • 3
  • 21
  • 43