SendInput()不产生任何可见的输出

本文关键字:任何可 输出 SendInput | 更新日期: 2023-09-27 18:14:08

我有问题获得SendInput函数产生任何类型的输出。所有结构体的定义如下(我把鼠标和硬件的都去掉了):

[StructLayout(LayoutKind.Explicit)]
    public struct INPUT
    {
        [FieldOffset(0)]
        public int type;
        [FieldOffset(8)]
        public MOUSEINPUT mi;
        [FieldOffset(8)]
        public KEYBDINPUT ki;
        [FieldOffset(8)]
        public HARDWAREINPUT hi;
    }
[StructLayout(LayoutKind.Sequential)]
    public struct KEYBDINPUT
    {
        public ushort wVk;
        public ushort wScan;
        public uint dwFlags;
        public uint time;
        public IntPtr dwExtraInfo;
    }

我以以下方式发送密钥:

SetForegroundWindow(hProc); // using user32.dll switch to desired process
// send keydown 
INPUT iKeyDown = new INPUT();
KEYBDINPUT sKeysDown = new KEYBDINPUT();
iKeyDown.type = KEYBD_INPUT_TYPE;
iKeyDown.ki = sKeysDown;
sKeysDown.wVk = 0;
sKeysDown.wScan = (ushort)0x1E;
sKeysDown.dwFlags = 0x0008 ;
sKeysDown.time = 0;
sKeysDown.dwExtraInfo = GetMessageExtraInfo();

我以完全相同的方式发送Key Up事件,除了dwFlags属性:

sKeysUp.dwFlags = 0x0008 | 0x0002;
最后,

INPUT[] aInputs = new INPUT[] { iKeyDown, iKeyUp };
uint result = SendInput(2, aInputs, Marshal.SizeOf(iKeyDown));  // when dll importing, SetLastError = true 
int error = Marshal.GetLastWin32Error();
Debug.WriteLine(result.ToString() + " " + error.ToString());

这样做的结果是,好吧,没有可见的输出,结果变量总是等于2(成功输入的数量),并且GetLastWin32Error()返回0(根据错误代码,它是成功的)。这里有我遗漏的东西吗?干杯!

SendInput()不产生任何可见的输出

我已经回答了我自己的问题-我填写结构不正确。而不是

INPUT iKeyDown = new INPUT();
KEYBDINPUT sKeysDown = new KEYBDINPUT();
iKeyDown.type = KEYBD_INPUT_TYPE;
iKeyDown.ki = sKeysDown;
sKeysDown.wVk = 0; // etc

我应该做

INPUT iKeyDown = new INPUT();
iKeyDown.type = KEYBD_INPUT_TYPE;
iKeyDown.ki.wvK = 0; // etc

。新的KEYBDINPUT()把事情搞砸了。我也把鼠标/键盘/硬件联合在自己的单独的结构,如GSerg建议。现在,它正按预期运作。