I am trying to use SendInput to send keystrokes. The code works for example if I try to send key A, but if I try right arrow key it types 6. Got no clue why.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);
[DllImport("user32.dll")]
internal static extern uint SendInput(
uint nInputs,
[MarshalAs(UnmanagedType.LPArray), In] INPUT[] pInputs,
int cbSize);
private void button1_Click(object sender, EventArgs e)
{
SetForegroundWindow(FindWindow("Notepad", "Untitled - Notepad"));
SendInputWithAPI();
}
void SendInputWithAPI()
{
INPUT[] Inputs = new INPUT[1];
INPUT Input = new INPUT();
Input.type = 1; // 1 = Keyboard Input
Input.U.ki.wScan = ScanCodeShort.RIGHT;
Input.U.ki.dwFlags = KEYEVENTF.SCANCODE;
Inputs[0] = Input;
SendInput(1, Inputs, INPUT.Size);
}
btw ScanCodeShort.RIGHT returns 77. Thanks.
Scan codes represent physical keys. With different keyboard layouts and states, the same physical key may have different meanings, but its scan code will always be the same. I.e. the physical "numpad 6" key may mean right arrow or number 6 depending on the state of Num Lock.
If your goal is to "press" the logical "right arrow", as opposed to a certain physical key on the physical keyboard regardless of its current meaning, you should use virtual keys codes instead. They represent the current meaning of the physical key. Assuming that your INPUT
structure declaration is correct:
private const int INPUT_KEYBOARD = 1;
private const int VK_RIGHT = 0x27;
Input.type = INPUT_KEYBOARD;
Input.U.ki.wVk = VK_RIGHT;
Inputs[0] = Input;