开发者

Detecting keystrokes

开发者 https://www.devze.com 2023-01-13 07:12 出处:网络
I need to detect a keystroke, without the user pressing enter. What\'s 开发者_开发问答the most elegant way?

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 enter, the program does something.


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).


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  
}


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

精彩评论

暂无评论...
验证码 换一张
取 消