Skip to content

Instantly share code, notes, and snippets.

@proteneer
Created February 6, 2014 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save proteneer/8839171 to your computer and use it in GitHub Desktop.
Save proteneer/8839171 to your computer and use it in GitHub Desktop.
Keyboard events Linux
#define LINUX
#ifndef LINUX
#include <conio.h> /* kbhit(), getch() */
#else
#include <sys/time.h> /* struct timeval, select() */
/* ICANON, ECHO, TCSANOW, struct termios */
#include <termios.h> /* tcgetattr(), tcsetattr() */
#include <cstdlib> /* atexit(), exit() */
#include <unistd.h> /* read() */
#include <cstdio> /* printf() */
#include <cstring>
#include <iostream>
using namespace std;
static struct termios g_old_kbd_mode;
/*****************************************************************************
*****************************************************************************/
static void cooked(void)
{
tcsetattr(0, TCSANOW, &g_old_kbd_mode);
}
/*****************************************************************************
*****************************************************************************/
static void raw(void)
{
static char init;
/**/
struct termios new_kbd_mode;
if(init)
return;
/* put keyboard (stdin, actually) in raw, unbuffered mode */
tcgetattr(0, &g_old_kbd_mode);
memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios));
new_kbd_mode.c_lflag &= ~(ICANON | ECHO);
new_kbd_mode.c_cc[VTIME] = 0;
new_kbd_mode.c_cc[VMIN] = 1;
tcsetattr(0, TCSANOW, &new_kbd_mode);
/* when we exit, go back to normal, "cooked" mode */
atexit(cooked);
init = 1;
}
/*****************************************************************************
*****************************************************************************/
void changemode(int dir)
{
static struct termios oldt, newt;
if ( dir == 1 )
{
tcgetattr( STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt);
}
else
tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
}
int kbhit (void)
{
struct timeval tv;
fd_set rdfs;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&rdfs);
FD_SET (STDIN_FILENO, &rdfs);
select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv);
return FD_ISSET(STDIN_FILENO, &rdfs);
}
/*****************************************************************************
*****************************************************************************/
static int getch(void)
{
unsigned char temp;
raw();
/* stdin = fd 0 */
if(read(0, &temp, 1) != 1)
return 0;
return temp;
}
#endif
int main() {
changemode(1);
while(true) {
if(kbhit()) {
cout << "keyboard event: " << char(getch()) << endl;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment