为什么 "If GetAsyncKeyState" 会无限发送 Button?

why does the "If GetAsyncKeyState" sends Button infinitely?

我想制作一个只有在我按下它时才会无限发送 space 的宏,问题是即使我离开按钮它也会发送它。

DWORD WINAPI BhopThread(LPVOID lp)
{
    while (true)
    {
        if (bhop)
        {
            if (GetAsyncKeyState(VK_SPACE))
                {
                Sleep(10);
                keybd_event(0x20, 0, 0, 0);
                Sleep(1);
                keybd_event(0x20, 0, KEYEVENTF_KEYUP, 0);
                Sleep(10);
                }
        }
    }
}

我做错了什么?

您必须检查 GetAsyncKeyState() 函数的 return 值的最高位以确定当前是否按下了它们的键。

GetAsyncKeyState() function

If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior;

简单地说,这意味着 GetAsyncKeyState() return 不只是真或假,而是一个广泛的值。要确定该键当前是否真的被按下,也就是被按下,您需要使用 位运算符 和值 0x8000.

检查 Space 键当前是否被按下的示例:

if(GetAsyncKeyState(VK_SPACE) & 0x8000)
{
    // high bit is set.  Space is currently held down.
} 

什么是位运算符?

这太宽泛了,无法在此答案中进行解释。我建议你有一些基本的 C++ books/docs/tutorials 来阅读。

https://en.wikipedia.org/wiki/Bitwise_operation#AND