- 论坛徽章:
- 0
|
搜寻了几天,终于搜到了直接终端获取按键的方法,根据自己的需要稍微修改了一下
现在贴上,算是个好的结束
- /*
- * getch() -- a blocking single character input from stdin
- *
- * Returns a character, or -1 if an input error occurs
- *
- * Conditionals allow compiling with or without echoing of the input
- * characters, and with or without flushing pre-existing buffered input
- * before blocking.
- */
- char _get_key( char echo, char flush )
- {
- struct termios old_termios, new_termios;
- int OPTIONAL_ACTIONS;
- int error, keylen;
- char cbuf[10];
-
- fflush( stdout );
- tcgetattr( 0, &old_termios );
- new_termios = old_termios;
- /*
- * raw mode, line settings
- */
- new_termios.c_lflag &= ~ICANON;
- if(echo)
- /*
- * enable echoing the char as it is typed
- */
- new_termios.c_lflag |= ECHO;
- else
- /*
- * disable echoing the char as it is typed
- */
- new_termios.c_lflag &= ~ECHO;
- if(flush)
- /*
- * use this to flush the input buffer before blocking for new input
- */
- OPTIONAL_ACTIONS = TCSAFLUSH;
- else
- /*
- * use this to return a char from the current input buffer, or block
- * if no input is waiting
- */
- OPTIONAL_ACTIONS = TCSANOW;
- /*
- * minimum chars to wait for
- */
- new_termios.c_cc[VMIN] = 1;
- /*
- * minimum wait time, 1 * 0.10s
- */
- new_termios.c_cc[VTIME] = 1;
- error = tcsetattr( 0, OPTIONAL_ACTIONS, &new_termios );
- _init_array(cbuf,sizeof(cbuf));
- if ( 0 == error )
- {
- /*
- * get char from stdin
- */
- keylen = read( 0, &cbuf, sizeof(cbuf) );
- }
- /*
- * restore old settings
- */
- error += tcsetattr( 0, OPTIONAL_ACTIONS, &old_termios );
- if(error == 0)
- {
- if(keylen == 1) return cbuf[0];
- return(_analysis_kcode(cbuf+1)); // analysis function key
- }
- else
- {
- return( -1);
- }
- } /* end of getch */
复制代码 |
|