如何使用GetAsyncKeyState而不调用它多次

How to use GetAsyncKeyState without calling it multiple times?

本文关键字:调用 何使用 GetAsyncKeyState      更新时间:2023-10-16

我的代码现在看起来是这样的:

    if (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState(0x31)) {
        //...
    }
    if (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState(0x32)) {
        //...
    }
    if (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState(0x33)) {
        //...
    }
    if (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState(0x34)) {
        //...
    }
    if (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState(0x35)) {
        //...
    }

有没有更有效的方法来做到这一点,而不调用GetAsyncKeyState多次每个循环?也许将函数值存储为整数,然后使用switch语句?

另外,我不想使用RegisterHotKey

以下是一些建议。0. 调用函数比直接使用一个值要慢。1. if-else语句可以构建一个树。该树应通过路径压缩进行优化。你可以这样提升你的代码:

static bool keys[256];
int getkey(){          //Don't forget to call this  before querying the "keys" array.
    for(int i=0;i<256;i++)
          GetAsyncKeyState(i);
    return 0;
}
if(keys[VK_CONTROL])
{
    if (keys[0x31]) {
        //...
    }
    if (keys[0x32]) {
       //...
    }
    if (keys[0x33]) {
        //...
    }
    if (keys[0x34]) {
        //...
    }
    if (keys[0x35]) {
        //...
    }
}