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;

 FD_ZERO(&rdfs);
 FD_SET(STDIN_FILENO, &rdfs);

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

 if(FD_ISSET(STDIN_FILENO, &rdfs))
 {
  int KeyCode = getchar();
  if(pKeyCode != NULL) *pKeyCode = KeyCode;
  KeyIsPressed = 1;
 }

 return KeyIsPressed;
}

Hope this will help...

0 Comments:

Post a Comment