Windows 系统下的 vs 中可以使用 _kbhit() 函数来获取键盘事件,使用时需要加入 conio.h 头文件,例:
实例
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
int ch;
while (1){
if (_kbhit()){//如果有按键按下,则_kbhit()函数返回真
ch = _getch();//使用_getch()函数获取按下的键值
cout << ch;
if (ch == 27){ break; }//当按下ESC时循环,ESC键的键值时27.
}
}
system("pause");
}
在 Unix/Linux 下,并没有提供 kbhit() 函数。我们可以自己来实现 kbhit() 程序。
实例
#include <stdio.h>
#include <termios.h>
static struct termios initial_settings, new_settings;
static int peek_character = -1;
void init_keyboard(void);
void close_keyboard(void);
int kbhit(void);
int readch(void);
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;
}
int main()
{
init_keyboard();
while(1)
{
kbhit();
printf("\n%d\n", readch());
}
close_keyboard();
return 0;
}