Check if any key is pressed in Linux

In case you would to know if a key (any key) is pressed in Windows it exist a very useful function called _kbhit(). Linux doesn't have a similar function but is possible to easily reproduce using a few lines of code. Nothing new since this kind of code is possible to find in many places around, it's just to give my little contribution by providing a ready made function to simply copy and past in your code.

Here the code. The function return 1 in case of key pressed and 0 in case of no key pressed. Optionally, in case of key pressed, you can get the key code by passing a pointer to an integer variable instead of passing NULL. Please note the function return immediately with the info about the key pressure and, in case of pressure detected, extract the key code from stdin stream.

int KeyPressed(int* pKeyCode)
 int KeyIsPressed = 0;
 struct timeval tv;
 fd_set rdfs;

 tv.tv_sec = tv.tv_usec = 0;


 select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv);

  int KeyCode = getchar();
  if(pKeyCode != NULL) *pKeyCode = KeyCode;
  KeyIsPressed = 1;

 return KeyIsPressed;

Hope this will help...


Popular posts from this blog

Access GPIO from Linux user space

Launch an app from Android shell terminal

Qt 5 and " Failed to load platform plugin 'windows' " error