#`SendInput` Only sending a single character, instead of holding down a key

2 messages · Page 1 of 1 (latest)

wanton yew
#

When I was working on a project I needed to be able to hold a key down, and chose SendInput since it apperantly works for DirectX games.

I've already tried: https://stackoverflow.com/questions/64084452/how-to-simulate-holding-down-a-key-in-c, https://www.youtube.com/watch?v=j4VFo4acorQ, and a whole lotta chatgpting.

I wrote this in Rust originally.

    let mut keybd_flags = KEYEVENTF_SCANCODE;
    let mut inserted_events = 0;
    let mut expected_events = 1;

    let mut input: INPUT = std::mem::zeroed();
    let mut kbd_input: KEYBDINPUT = std::mem::zeroed();
    kbd_input.wScan = scan_code as u16;
    kbd_input.dwFlags = keybd_flags;
    input.type_ = INPUT_KEYBOARD;
    *input.u.ki_mut() = kbd_input;

    let new_events = SendInput(1, std::ptr::addr_of_mut!(input), INPUT_SIZE);
    inserted_events += new_events;

    if inserted_events != expected_events {
        return Err(Error::InputError(inserted_events as i32));
    }
    std::thread::sleep(std::time::Duration::from_millis(1));

This would only press a key a single time not actually holding it down, (as tested in vscode and notepad). As shown below:

    unsafe { key_down("a").unwrap() }
    sleep(3.0);
    unsafe { key_up("a").unwrap() }

So I assumed there was a problem with my code, I decided to look for something online in C++ that accomplishes the same task and test with that.

Which is when I came across this:

    WCHAR key = 'a';
    key = VkKeyScanW(key);
    UINT mappedKey = MapVirtualKeyW(LOBYTE(key), NULL);
    INPUT input = { 0 };
    input.type = INPUT_KEYBOARD;
    input.ki.dwFlags = KEYEVENTF_SCANCODE;
    input.ki.wScan = mappedKey;
    SendInput(1, &input, sizeof(input));
    Sleep(2000);
    input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
    SendInput(1, &input, sizeof(input));

But I face the same difficulty here, where a is only pressed a single time.

For context, I'm attempting to copy the functionality from pydirectinput into rust, which follows that functionality. Yet keyDown on pydirectinput works as intended.

So I'm a little lost, also go easy on me I'm extremely new to using the WinAPI and for the most part have been scavenging code and whatever I can learn off Google.

(pasted from stack overflow)

This video explaines how to simulate mouse and keyboard events in C++
This methods can be used for instance when writing a simple click bot

Support the channel:

▶ Play video
gilded sage