我可以在main()函数之外使用GetAsyncKeyState()吗?

时间:2015-05-07 16:37:40

标签: c++ c winapi keyboard main

我写作,只是为了对编程程序有信心,这是一个响应键盘输入的win32应用程序。为此,我使用了GetAsyncKeyState()功能。

起初我在main()函数中编写了所有代码,一切看起来都很好,但它确实有效。所以我决定使事情复杂化,但这需要我在GetAsyncKeyState()调用的不同函数中使用main()函数。我以为我只需要在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; 
}

当我运行这段代码时,循环继续进行,如果我按下键不重要,它会保持循环而不打印任何东西。任何帮助都会受到很大的影响。

1 个答案:

答案 0 :(得分:0)

您的问题与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;
}