如何使keybd_event连续三次击中tab

本文关键字:三次 tab keybd 何使 event 连续 | 更新日期: 2023-09-27 18:16:18

我现在有这个代码

 keybd_event(0x09, 0, 0, 0);
 keybd_event(0x09, 0, 0, 0);
 keybd_event(0x09, 0, 0, 0);

可以连续三次按TAB键,但是,它只按第一次TAB键,不会再按TAB键。

当我尝试调试它时,每当我继续到第二个和第三个keybd_event时,它显示消息"代码运行时不允许更改"

如何使keybd_event连续三次击中tab

您没有在每次击键之间发送任何KEYEVENTF_KEYUP事件,例如:

keybd_event(0x09, 0, 0, 0);
keybd_event(0x09, KEYEVENTF_KEYUP, 0, 0);
keybd_event(0x09, 0, 0, 0);
keybd_event(0x09, KEYEVENTF_KEYUP, 0, 0);
keybd_event(0x09, 0, 0, 0);
keybd_event(0x09, KEYEVENTF_KEYUP, 0, 0);

也就是说,keybd_event()是递减的,你应该使用SendInput()来代替(参见user32.dll中通过SendInput发送密钥),例如:

INPUT input = new INPUT {
    Type = 1
};
input.Data.Keyboard = new KEYBDINPUT() {
    Vk = 0x09,
    Scan = 0,
    Flags = 0,
    Time = 0,
    ExtraInfo = IntPtr.Zero,
};
INPUT input2 = new INPUT {
    Type = 1
};
input2.Data.Keyboard = new KEYBDINPUT() {
    Vk = 0x09,
    Scan = 0,
    Flags = 2,
    Time = 0,
    ExtraInfo = IntPtr.Zero
};
INPUT[] inputs = new INPUT[] { input, input2, input, input2, input, input2 };
SendInput(6, inputs, Marshal.SizeOf(typeof(INPUT)));

或者,您可以使用SendKeys()代替,例如:

SendKeys.Send("{TAB}{TAB}{TAB}");