Following the recommendations of this topic: distinguish between keystrokes Real and Virtual
I am trying to create a program that will send keyboard keystroke events using the SendInput () method .
However, the problem is that when I try to simulate a keypress event, nothing happens. So far, my code is:
[DllImport("user32.dll")]
static extern UInt32 SendInput(UInt32 nInputs, [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] INPUT[] pInputs, Int32 cbSize);
[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
public short wScan; public int dwFlags;
public int time; public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Explicit)]
struct INPUT
{
[FieldOffset(0)] public int type;
[FieldOffset(8)] public KEYBDINPUT ki;
}
const int KEYEVENTF_DOWN = 0;
const int KEYEVENTF_EXTENDEDKEY = 0x0001;
const int KEYEVENTF_KEYUP = 0x0002;
const int KEYEVENTF_UNICODE = 0x0004;
const int KEYEVENTF_SCANCODE = 0x0008;
public void Send_Key(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)));
}
To decrypt scancodes, I downloaded the program that was proposed in this thread:
https://superuser.com/questions/293609/windows-7-tool-to-capture-keyboard-scan-codes
according to this program - "a" key code for my keyboard - "65"
, , "q" - "q" send_key(), "qa":
private void textBox2_TextChanged(object sender, EventArgs e)
{
Send_Key(0x0065);
}
? , ( DOWN UP). , , keyUP.
: , , , , , .
public void Send_Key(short Keycode)
{
INPUT[] InputData = new INPUT[1];
InputData[0].type = 1;
InputData[0].ki.wScan = Keycode;
InputData[0].ki.dwFlags = KEYEVENTF_DOWN;
InputData[0].ki.time = 0;
InputData[0].ki.dwExtraInfo = IntPtr.Zero;
uint intReturn = SendInput(1, InputData, Marshal.SizeOf(typeof(INPUT)));
if (intReturn == 0)
{
throw new Exception("Could not send keyDOWN: " + Keycode);
}
INPUT[] InputData2 = new INPUT[1];
InputData2[0].type = 1;
InputData2[0].ki.wScan = Keycode;
InputData2[0].mi.dwFlags = KEYEVENTF_KEYUP;
InputData2[0].ki.time = 0;
InputData2[0].ki.dwExtraInfo = IntPtr.Zero;
uint intReturn2 = SendInput(1, InputData2, Marshal.SizeOf(typeof(INPUT)));
if (intReturn2 == 0)
{
throw new Exception("Could not send keyUP: " + Keycode);
}
}
.. .