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

标签 c++ c winapi keyboard program-entry-point

我正在编写一个响应键盘输入的 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; 
}

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

最佳答案

你的问题与main()无关。可以调用winapi函数如GetAsyncKeyState()只要您提供好的参数,就可以在代码中的任何位置进行操作。

根据这个列表virtual key codes代码 0x4c 对应于 key L,而不是 key 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;
}

关于c++ - 我可以在 main() 函数之外使用 GetAsyncKeyState() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30106965/

相关文章:

c++ - 从 C++ 中的不同项目中调用函数(在 Linux 中)

c++ - Ofstream 拒绝带参数的输入

c++ - 为 C++ 设置窗口

C编程读取文件

c - 如何在 DOS/C 中访问非标准 COM 端口(USB->Serial,COM5+)?

c++ - 将 C API 调用转换为 delphi

c - Windows 上的 InternetOpenUrl 函数是否足够安全?如果没有,如何让它更强大?

c++ shared_ptr with std::function or double (*SOME_NAME)(double);

c++ - 使用作业对象限制 Windows 进程内存/执行时间 - 我的代码有什么问题?

c - 仅递归地添加偶数