看看哪位高手能用gcc实现这个不回显非阻塞键盘输入的超简单TC,VC程序,不是高手恐怕做不到
看看谁能用gcc实现这个不回显非阻塞键盘输入的超简单TC,VC程序,不是高手恐怕做不到
------解决方案--------------------
Linux下使用NCURSES库
------解决方案--------------------
------解决方案--------------------
- C/C++ code
TC程序如下: #include <stdio.h> #define esc 27 main() { int key,i=1; while(1) { printf("+"); sleep(1); if (i++>=5) {i=1; system("cls");} while(kbhit()) { key=getch(); if (key==esc) {exit (0);} printf("%c ",key); } } }
------解决方案--------------------
Linux下使用NCURSES库
------解决方案--------------------
------解决方案--------------------
- C/C++ code
//编译和连接命令: gcc <程序文件> -lncurses include <ncurses.h> int main() { initscr(); /* 初始化,进入 NCURSES 模式 */ printw("Hello World !!!"); /* 在虚拟屏幕上打印 Hello, World!!! */ refresh(); /* 将虚拟屏幕上的内容写到显示器上,并刷新 */ getch(); /* 等待用户输入 */ endwin(); /* 退出 NCURSES 模式 */ return 0; }
------解决方案--------------------
NCURSES-Programming-HOWTO-CN.pdf
------解决方案--------------------
方向键不能以一个ascii码表示,需要用escape转义,比如向上键是^[[A,^[代表esc
所以你按方向键会碰到esc
------解决方案--------------------
getch使用224转义,这个msdn上有说明
------解决方案--------------------
就是27,你无法区分向上键和顺次输入的esc [ A
------解决方案--------------------
如果看到esc,检测是否有下一个字符,下一个字符是不是[
------解决方案--------------------
核心不就是要自己实现 kbhit和getch嘛,给你贴段代码。
- C/C++ code
/** * file encode: UTF-8 * date: 12-03-2010 * author: Vincent * msn: */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <termios.h> #include <errno.h> #include <string.h> /********************************** * defination * **********************************/ #define ESC 27 #define ENTER 10 #define BACKSPACE 127 static struct termios initial_settings, new_settings; static int peek_character = -1; void init_keyboard(); void close_keyboard(); int kbhit(); int readch(); /******************************* * implementation * *******************************/ int main(int argc, char* argv[]) { int ch; ch = 0; init_keyboard(); while(ESC != ch) { if(kbhit()) { ch = readch(); switch(ch) { case ESC: break; } } } close_keyboard(); return 0; } void init_keyboard() { tcgetattr(0, &initial_settings); new_settings = initial_settings; new_settings.c_lflag &= ~ICANON; new_settings.c_lflag &= ~ECHO; new_settings.c_lflag &= ~ISIG; new_settings.c_cc[VMIN] = 1; new_settings.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &new_settings); return; } void close_keyboard() { tcsetattr(0, TCSANOW, &initial_settings); return; } int kbhit() { char ch; int nread; if(-1 != peek_character) { return 1; } new_settings.c_cc[VMIN] = 0; tcsetattr(0, TCSANOW, &new_settings); nread = read(0, &ch, 1); new_settings.c_cc[VMIN] = 1; tcsetattr(0, TCSANOW, &new_settings); if(1 == nread) { peek_character = ch; return 1; } return 0; } int readch() { char ch; if(-1 != peek_character) { ch = peek_character; peek_character = -1; return ch; } read(0, &ch, 1); return ch; }