I'm trying to simulate keyboard input to a certain process using c#. Inputting chars and numbers works fine, but when I try to simulate a "special character" (ENTER, TAB, etc.) key press, nothing happens.
What blows my mind is that simulating these special characters works fine on other processes such as Skype.
Any ideas of what might cause this weird interaction? I'm open to trying things in other languages as well since I haven't gotten that far in my project.
I have tried using SendInput() and PostMessage() and they both share the same result, inputing chars works, but not special keys.
I managed to solve it. I'll post my solution in case someone happens to stumble upon this post with the same problem I had.
The solution is actually rather simple. If you instead of sending virtual key codes send keyboard scan codes, everything works fine. Here's a quick example.
using System.Runtime.InteropServices;
...
public static void PressEnter()
{
INPUT input = new INPUT();
input.type = (int)InputType.INPUT_KEYBOARD;
input.ki.wScan = 0x1C;
input.ki.dwFlags = (int)KEYEVENTF.SCANCODE;
input.ki.dwExtraInfo = GetMessageExtraInfo();
var arrayToSend = new INPUT[] { input };
SendInput(1, arrayToSend, Marshal.SizeOf(input)); //Send KeyDown
arrayToSend[0].ki.dwFlags = (int)KEYEVENTF.SCANCODE | (int)KEYEVENTF.KEYUP;
SendInput(1, arrayToSend, Marshal.SizeOf(input)); //Send KeyUp
}
Other necessary info:
[StructLayout(LayoutKind.Explicit)]
public struct INPUT
{
[FieldOffset(4)]
public HARDWAREINPUT hi;
[FieldOffset(4)]
public KEYBDINPUT ki;
[FieldOffset(4)]
public MOUSEINPUT mi;
[FieldOffset(0)]
public int type;
}
[StructLayout(LayoutKind.Sequential)]
public struct HARDWAREINPUT
{
public int uMsg;
public short wParamL;
public short wParamH;
}
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct KEYBDINPUT
{
public short wVk;
public short wScan;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
[Flags]
public enum InputType
{
INPUT_MOUSE = 0,
INPUT_KEYBOARD = 1,
INPUT_HARDWARE = 2
}
[Flags]
public enum KEYEVENTF
{
KEYDOWN = 0,
EXTENDEDKEY = 0x0001,
KEYUP = 0x0002,
UNICODE = 0x0004,
SCANCODE = 0x0008,
}
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetMessageExtraInfo();
[DllImport("user32.dll", SetLastError = true)]
public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);