Search code examples
c#directxsendinput

Simulating Keyboard with SendInput C#


I tried to simulate a key from the keyboard for a direct x game with this code:

public static void Send(short Keycode)
{
    INPUT[] InputData = new INPUT[1];

    InputData[0].type = 1;
    InputData[0].ki.wScan = Keycode;
    InputData[0].ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE;
    InputData[0].ki.time = 0;
    InputData[0].ki.dwExtraInfo = IntPtr.Zero;

    SendInput(1, InputData, Marshal.SizeOf(typeof(INPUT)));
}

The problem is, this does not simulate the key. The key isn't pressed.


Solution

  • You need to send a KEYEVENTF_KEYDOWN and then a KEYEVENTF_KEYUP event in order for the game to correctly process the key events.

    Leave a little pause in between the sending of the key events.

    This is needed if the game is polling the keys, it then has time to recognize the pressed key.