Automating Key Presses with SendInput

我的梦境 提交于 2019-11-29 17:30:49

For the benefit of others that are searching for how to use SendInput() in C#, please see the below description.

1) There are two ways to send the key stroke with SendInput(), either using a Scancode or a virtual-key code

2) If you intend to send keystrokes to a game or another application that takes input from Direct 3D (or another DirectInput environment), you need to send the key strokes as scancodes, and therefor you specify the wScan field, and leave wVk blank. See info here: KEYBDINPUT

3) Remember to switch the window in focus to the application you want to send keystrokes to, before sending the keystroke. Example:

MemoryHandler.SwitchWindow(Process.GetProcessesByName("notepad").FirstOrDefault().MainWindowHandle);

4) Final code:

    public static void PressKey(char ch, bool press)
    {
        byte vk = MemoryApi.VkKeyScan(ch);
        PressKey((MemoryApi.KeyCode)vk, press);
    }

    public static void PressKey(MemoryApi.KeyCode vk, bool press)
    {
        ushort scanCode = (ushort)MemoryApi.MapVirtualKey((ushort)vk, 0);

        //Console.WriteLine("SendInput:: VK: " + (ushort)vk + " (" + vk + ") <-> SC: " + (ushort)(scanCode & 0xff));

        if (press)
            KeyDown(scanCode);
        else
            KeyUp(scanCode);
    }

    public static void KeyDown(ushort scanCode)
    {
        //Console.WriteLine("Key Down (SC): " + (ushort)(scanCode & 0xff));
        MemoryApi.INPUT[] inputs = new MemoryApi.INPUT[1];

        inputs[0].type = MemoryApi.INPUT_KEYBOARD;
        inputs[0].ki.wScan = (ushort)(scanCode & 0xff);
        inputs[0].ki.dwFlags = MemoryApi.KEYEVENTF_SCANCODE;
        inputs[0].ki.time = 0;
        inputs[0].ki.dwExtraInfo = IntPtr.Zero;

        uint intReturn = MemoryApi.SendInput(1, inputs, Marshal.SizeOf(inputs[0]));
        if (intReturn != 1)
        {
            throw new Exception("Could not send key: " + scanCode);
        }
    }

    public static void KeyUp(ushort scanCode)
    {
        //Console.WriteLine("Key Up (SC): " + scanCode);
        MemoryApi.INPUT[] inputs = new MemoryApi.INPUT[1];

        inputs[0].type = MemoryApi.INPUT_KEYBOARD;
        inputs[0].ki.wScan = (ushort)(scanCode & 0xff);
        inputs[0].ki.dwFlags = MemoryApi.KEYEVENTF_SCANCODE | MemoryApi.KEYEVENTF_KEYUP;
        inputs[0].ki.time = 0;
        inputs[0].ki.dwExtraInfo = IntPtr.Zero;

        uint intReturn = MemoryApi.SendInput(1, inputs, Marshal.SizeOf(inputs[0]));
        if (intReturn != 1)
        {
            throw new Exception("Could not send key: " + scanCode);
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!