[英]Can I use GetAsyncKeyState() outside of the main() function?
我在写,只是为了对编程过程有信心,它是一个响应键盘输入的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;
}
当我运行此代码时,循环继续进行,无论是否按下键都无关紧要,循环不断进行而无需打印任何内容。 任何帮助将不胜感激。
您的问题与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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.