【问题标题】:Can I use GetAsyncKeyState() outside of the main() function?我可以在 main() 函数之外使用 GetAsyncKeyState() 吗?
【发布时间】:2015-07-18 08:58:49
【问题描述】:

我正在编写一个响应键盘输入的 win32 应用程序,只是为了获得对编程过程的信心。为此,我使用了GetAsyncKeyState() 函数。

起初,我将所有代码都写在main() 函数中,一切似乎都很好,它确实有效。所以我决定让事情复杂化,但这需要我在main() 调用的另一个函数中使用GetAsyncKeyState() 函数。我以为我只需要在main() 之外声明一些变量并将代码从main 移动到新函数,如下所示:

int btnup_down = 0; 
int close = 1; 
int main(void){
    while (1){
        Sleep(50);
        listentokb();
        if (close == 0){
            break;
        }
    }return 0;
}
int listentokb(void){ 
    if ((GetAsyncKeyState(0x4C) & 0x8000) && (ko == 0)){ 
        ko = 1; 
        printf("Ok you pressed k"); 
        return 0; 
    } else if (((GetAsyncKeyState(0x4C) == 0) && (ko == 1))  { 
        ko = 0; 
        printf("Now you released it"); 
        close = 0; 
        return 0; 
    }return 0; 
}

当我运行此代码时,循环继续进行,无论我是否按下键,它都会继续循环,而不会打印任何内容。任何帮助将不胜感激。

【问题讨论】:

  • 你当然不需要全局变量。此外,0x4C 是 L 键。

标签: c++ c winapi keyboard main


【解决方案1】:

您的问题与main() 无关。您可以在代码中的任何位置调用诸如GetAsyncKeyState() 之类的winapi 函数,只要您提供好的参数即可。

根据virtual key codes 的这个列表,代码 0x4c 对应于键 L 而不是键 K。因此,在您的代码中括号更正错字之后,我可以成功运行它并使用 L

中断循环

关于你的功能的一些评论:

您的函数listentokb() 始终返回0。另一方面,您使用全局变量close 告诉调用函数您的键盘扫描结果。这是一个非常糟糕的做法:尽可能避免使用全局变量。

这里有一个稍微更新的代码版本,它禁止全局变量,并使用返回值来传达结果:

const int KEY_K = 0x4B;    // avoid using values directly in the code

int listentokb (void){  // returns 'K' if K is released and 0 otherwise
    static int ko;      // this is like a global variable: it will keep the value from one call to the other
                        // but it has teh advantage of being seen only by your function
    if((GetAsyncKeyState(KEY_K) & 0x8000) && (ko == 0)){
        ko = 1;
        printf("Ok you pressed k");
        return 0;
    }
    else if((GetAsyncKeyState(KEY_K) == 0) && (ko == 1))  {
        ko = 0;
        printf("Now you released it");
        return 'K'; 
    }
    return 0;
}
int main(void){
    bool go_on = true;   // The state of the loop shall be local variable not global
    while(go_on){
        Sleep(50);
        go_on= ! listentokb();  // if returns 0  we go on
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2010-10-04
    • 2011-06-05
    • 2022-01-04
    • 2020-01-06
    • 1970-01-01
    相关资源
    最近更新 更多