Keystroke detection

I need to detect a keystroke, without user input. What is the most elegant way?

those. If the user clicks on a letter Qwithout clicking enter, the program does something.

+3
source share
3 answers

On unix / posix, the standard way to do this is to enter non-canonical mode using tcsetattr:

#include <termios.h>
#include <unistd.h>
    :
struct termios attr;
tcgetattr(0, &attr);
attr.c_lflag &= ~ICANON;
tcsetattr(0, TCSANOW, &attr);

See the termios (3) man page for more details (and probably more information than you would like to know).

+4
source

There is no good way to do this portable, as far as I know, other than using a type library ncursesthat provides a function getch(void).

. getchar(void) from stdio.h , , , .

+1

Windows <conio.h>provides a function _getch(void)that can be used to read keystrokes without an echo (print them yourself if you want).

#include <conio.h>
#include <stdio.h>

int main( void )
{
   int ch;

   puts( "Type '@' to exit : " );
   do
   {
      ch = _getch();
      _putch( ch );
   } while( ch != '@' );

   _putch( '\r' );    // Carriage return
   _putch( '\n' );    // Line feed  
}
+1
source

Source: https://habr.com/ru/post/1761628/