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

Can I use GetAsyncKeyState() outside of the main() function?

本文关键字:GetAsyncKeyState main 函数 我可以      更新时间:2023-10-16

我正在编写一个响应键盘输入的 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(),只要您提供良好的参数即可。

根据此虚拟键代码列表,代码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;
}
相关文章:
  • 没有找到相关文章