有没有一种方法可以检测是否已按下某个键? [英] Is there a way to detect if a key has been pressed?
问题描述
我正在Windows计算机上的cygwin中编译和执行我的程序.我对C没有足够的经验,但是我想提供一种在不提示用户的情况下(例如我)检测是否已按下某个键的方法.我的伪代码具有理想的功能,如下所示.
I am compiling and executing my programs in cygwin on a windows computer. I am quite inexperienced in C but I would like a way to detect if a key has been pressed without prompting the user(e.g me). My pseudo code with desirable functions is shown below.
char ch;
while(1){
if(KeyBeenPressed()){
//a key has been pressed before getting here
ch=getKeyPressed();
if(ch=='0'){
printf("you have pressed 0");
}
else{
printf("you did't press key 0");
}
}
//do other stuff
}
下面显示了我自己在搜索网络后解决此问题的尝试.
And my own try to solving this after searching the web is shown below.
#include <stdio.h>
#include <conio.h>
char ch;
void main(){
while(1){
if(kbhit()){ //kbhit is 1 if a key has been pressed
ch=getch();
printf("pressed key was: %c", ch);
}
}
}
此代码的问题是找不到conio.h文件(而且我还没有找到解决此问题的任何其他方法).显然,gcc编译器无法处理conio.h(我已将链接附加到它所在的位置). http://www.programmingsimplified.com/c/conio.h
A problem with this code is that the conio.h file can't be found(and I haven't found any other way to solve this). Apparently gcc compilers can't handle conio.h(I have attached the link to were it stood). http://www.programmingsimplified.com/c/conio.h
所以我想知道你们中是否有人知道一种方法来检测C中是否已按下某个键,所以我也想最好以char形式检索该按下的键(我打算在此应用程序中使用0-9) .重要的是该程序不能等到按下一个键.
So I wonder if any of you guys know a way to detect if a key has been pressed in C, I would also like to retrieve the pressed key preferably in a char (I plan on using 0-9 for this application). The important thing is that the program can't wait until a key is pressed.
我很感谢能解决这个问题的任何建议! 最好的祝福 亨里克
I am thankful for any suggestions that could solve this! Best regards Henrik
推荐答案
我对kbhit()
使用以下函数.它可以在Ubuntu上的g ++编译器上正常工作.
I use the following function for kbhit()
. It works fine on g++ compiler in Ubuntu.
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
这篇关于有没有一种方法可以检测是否已按下某个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!