简体   繁体   中英

Quickly press this key when a specific key is pressed. How prevent the trigger key to be pressed? (c++)

I'm sorry if the title is unclear.. buuut I didn't know how to put things shorter:c The (extract) code below is supposed to quickly press / send key 'A' if key 'U' is pressed / sent. But if I press 'U' it will first send 'U', then several 'A' right after. How can I make it such that key 'U' is not sent at all? I have tried different things but I couldn't get it to work... I think the problem lies within the if-condition:/

INPUT ip; // Structure for creating keyboard-events
ip.type = INPUT_KEYBOARD; // Create a generic keyboard-event
ip.ki.wScan = 0;       // Hardware-Scan-Code for the key
ip.ki.time = 0;        //
ip.ki.dwExtraInfo = 0; //

for (;;) {
    sleep_for(milliseconds(1)); // Sleep in each iteration so the CPU / RAM have a relaxed life
    if (GetAsyncKeyState(0x55)) {   // If key 'U' is pressed
        ip.ki.wVk = 0x41;                 // Press key 'A'
        ip.ki.dwFlags = 0;                //
        SendInput(1, &ip, sizeof(INPUT)); //

        ip.ki.dwFlags = KEYEVENTF_KEYUP;    // Release key that was pressed
        SendInput(1, &ip, sizeof(INPUT));   //
    }
}

You're calling GetAsyncKeyState() in a loop. If detects if the key is pressed down. It is calling the function multiple times during the time that key is pressed. When you press a key it's typically for 5-25 milliseconds, so GetASyncKeyState() is detecting the key press multiple times.

GetASyncKeyState() returns a short integer, if the least significant bit is set, then the key was already detected in a previous call to GetASyncKeyState()

To fix your code, just check this bit using the bitwise operator AND

if (GetAsyncKeyState(0x55) &1)

This is also useful when toggling booleans or features.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM