When I attempt to use SendInput
to send single key presses, and combined keypresses, I can't get my program to hold the keyboard button until commanded to be released. With the code below I am ables to send the character 'a'
, and 'A'
, by hitting shift first. However, I cannot get it to hold the 'a'
button in perpetuity.
public static void KeyDown()
{
SwitchWindow(Process.GetProcessesByName("notepad").FirstOrDefault().MainWindowHandle);
INPUT[] inputs = new INPUT[1];
KEYBDINPUT kb = new KEYBDINPUT();
//Set up generic keyboard event
inputs[0].type = INPUT_KEYBOARD;
kb.wScan = 0; // hardware scan code for key
kb.time = 0;
kb.dwExtraInfo = IntPtr.Zero;
kb.dwFlags = 0; // 0 for key press
//Press shift
kb.wVk = (ushort)KeyCode.SHIFT;
inputs[0].ki = kb;
SendInput(1, inputs, Marshal.SizeOf(inputs[0]));
//Press 'a' key
kb.wVk = (ushort)0x41; // virtual-key code for the "a" key
inputs[0].ki = kb;
SendInput(1, inputs, Marshal.SizeOf(inputs[0]));
//Release 'a' key
kb.dwFlags = KEYEVENTF_KEYUP;
kb.wVk = (ushort)0x41; // virtual-key code for the "a" key
inputs[0].ki = kb;
SendInput(1, inputs, Marshal.SizeOf(inputs[0]));
//Release 'shift' key
kb.dwFlags = KEYEVENTF_KEYUP;
kb.wVk = (ushort)KeyCode.SHIFT; // virtual-key code for the "a" key
inputs[0].ki = kb;
SendInput(1, inputs, Marshal.SizeOf(inputs[0]));
}
Any idea why, if I remove the last two SendInput
s, it doesn't just hold 'A'
down?