在linux下C语言实现对键盘事件的监听

来源:互联网 发布:web后端编程语言 编辑:程序博客网 时间:2024/05/21 13:28
我们知道,在windows下有个键盘测试函数,int kbhit(void)。使用该函数需要包含头文件conio.h。执行时,kbhit测试是否有键盘按键按下,若有则返回非零值,否则返回零。

在Unix/Linux下,并没有提供这个函数。在linux下开发控制台程序时,有时会遇到检测键盘是否有被按下的情况,这时就需要自己编写kbhit()实现的程序了。下面是kbhit在Unix/Linux下的一个实现。用到了一种终端操作库termios。

下面是头文件kbhit.h:
QUOTE:#ifndef KBHITh
#define KBHITh

void init_keyboard(void);
void close_keyboard(void);
int kbhit(void);
int readch(void);

#endif
下面式源程序kbhit.c:
QUOTE:#include "kbhit.h"
#include <stdio.h>
#include <termios.h>

static struct termios initial_settings, new_settings;
static int peek_character = -1;

void init_keyboard()
{
tcgetattr(0,&initial_settings);
new_settings = initial_settings;
new_settings.c_lflag &= ~ICANON;
new_settings.c_lflag &= ~ECHO;
new_settings.c_lflag &= ~ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}

void close_keyboard()
{
tcsetattr(0, TCSANOW, &initial_settings);
}

int kbhit()
{
unsigned char ch;
int nread;

if (peek_character != -1) return 1;
new_settings.c_cc[VMIN]=0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0,&ch,1);
new_settings.c_cc[VMIN]=1;
tcsetattr(0, TCSANOW, &new_settings);
if(nread == 1)
{
peek_character = ch;
return 1;
}
return 0;
}

int readch()
{
char ch;

if(peek_character != -1)
{
ch = peek_character;
peek_character = -1;
return ch;
}
read(0,&ch,1);
return ch;
}
原创粉丝点击