简体   繁体   English

按下特定键时快速按下此键。 如何防止触发键被按下? (c++)

[英]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.如果标题不清楚,我很抱歉.. buuut 我不知道如何缩短内容:c 如果按下/发送键“U”,下面的(提取)代码应该快速按下/发送键“A” . But if I press 'U' it will first send 'U', then several 'A' right after.但是如果我按'U',它会先发送'U',然后是几个'A'。 How can I make it such that key 'U' is not sent at all?我怎样才能使它根本不发送密钥'U'? I have tried different things but I couldn't get it to work... I think the problem lies within the if-condition:/我尝试了不同的东西,但我无法让它工作......我认为问题出在 if 条件中:/

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.您在循环中调用 GetAsyncKeyState() 。 If detects if the key is pressed down.如果检测到按键是否被按下。 It is calling the function multiple times during the time that key is pressed.在按下该键期间,它多次调用 function。 When you press a key it's typically for 5-25 milliseconds, so GetASyncKeyState() is detecting the key press multiple times.当您按下一个键时,通常会持续 5-25 毫秒,因此 GetASyncKeyState() 会多次检测按键。

GetASyncKeyState() returns a short integer, if the least significant bit is set, then the key was already detected in a previous call to GetASyncKeyState() GetASyncKeyState() 返回一个短的 integer,如果设置了最低有效位,则在之前对 GetASyncKeyState() 的调用中已经检测到密钥

To fix your code, just check this bit using the bitwise operator AND要修复您的代码,只需使用按位运算符 AND 检查此位

if (GetAsyncKeyState(0x55) &1)

This is also useful when toggling booleans or features.这在切换布尔值或特征时也很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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