En Visual Studio en sistemas Windows, se puede usar la función _kbhit() para obtener eventos de teclado. Al usarla, se necesita incluir el archivo de cabecera conio.h, por ejemplo:
Ejemplo
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
int ch;
while (1){
if (_kbhit()){//Si hay una tecla presionada, la función _kbhit() devuelve verdadero
ch = _getch();//Usar la función _getch() para obtener el valor de la tecla presionada
cout << ch;
if (ch == 27){ break; }//El bucle se ejecuta cuando se presiona ESC; el valor de la tecla ESC es 27.
}
}
system("pause");
}
En Unix/Linux, no se proporciona la función kbhit(). Podemos implementar el programa kbhit() nosotros mismos.
Ejemplo
#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;
}