Detecting keystrokes

前端 未结 3 869
清歌不尽
清歌不尽 2020-12-17 04:05

I need to detect a keystroke, without the user pressing enter. What\'s the most elegant way?

I.e. If the user hits the letter Q, without pressing ent

相关标签:
3条回答
  • 2020-12-17 04:52

    In Windows <conio.h> provides function _getch(void) which can be used to read keystroke without echo-ing them (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  
    }
    
    0 讨论(0)
  • 2020-12-17 04:58

    In unix/posix, the standard way of doing this is to put the input into non-canonical mode with 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 wanted to know).

    0 讨论(0)
  • 2020-12-17 05:05

    Theres no good way to do this portably, as far as I know, other than to use a library like ncurses, which provides the getch(void) function.

    Note: It appears getchar(void) from stdio.h waits until the enter key is pressed then feeds your the characters,s o it won't work.

    0 讨论(0)
提交回复
热议问题