Tony Zeyork Lin Tony Zeyork Lin - 1 month ago 14
C# Question

How to make keybd_event hit tab three consecutive times

I currently have this code

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


to be able to hit tab three consecutive times, however, it only hits tab the first time and wont hit tab again.

When I try to debug it, whenever I continue to the second and third keybd_event, it shows the message "changes are not allowed while code is running"

Answer

You need to send KEYEVENTF_KEYUP events after each keystroke, eg:

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);

That being said, you should be using SendInput() instead of keybd_event() (see Send keys through SendInput in user32.dll), eg:

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)));

Or even use SendKeys() instead:

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