根据此主题的建议,我正在尝试创建一个程序,使用SendInput()方法发送键盘按键事件。
然而,问题是当我尝试模拟按键事件时,根本没有任何反应。目前我的代码如下:
[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; //x64 - 8, x32 - 4
}
const int KEYEVENTF_DOWN = 0; //key UP
const int KEYEVENTF_EXTENDEDKEY = 0x0001;
const int KEYEVENTF_KEYUP = 0x0002; //key UP
const int KEYEVENTF_UNICODE = 0x0004;
const int KEYEVENTF_SCANCODE = 0x0008; // scancode
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)));
}
为了解密扫描码,我下载了本帖中建议的程序:https://superuser.com/questions/293609/windows-7-tool-to-capture-keyboard-scan-codes。根据这个程序的显示,我的键盘上按下"a"键的代码是"65"。
我的程序被设计成在文本框文本更改时触发按键事件,所以如果我们输入"q",文本应该更改为"q"再加上send_key()的结果,即"qa":
private void textBox2_TextChanged(object sender, EventArgs e)
{
Send_Key(0x0065); // nothing happens (0x65 also fails)
}
我做错了什么?将来我会更改这段代码,以便可以指定按键保持时间(在DOWN和UP事件之间)。但是现在,出于测试目的,我只模拟按键抬起事件。
编辑:汉斯,根据您的建议进行了编辑-但不幸的是,它无法正常工作。
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) //!=1
{
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; // KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE;
InputData2[0].ki.time = 0;
InputData2[0].ki.dwExtraInfo = IntPtr.Zero;
uint intReturn2 = SendInput(1, InputData2, Marshal.SizeOf(typeof(INPUT)));
if (intReturn2 == 0) //!=1
{
throw new Exception("Could not send keyUP: " + Keycode);
}
}
没有错误,也没有输出。