看看谁能用gcc实现这个不回显非阻塞键盘输入的超简单TC,VC程序,不是高手恐怕做不到
- C/C++ code
TC程序如下:#include <stdio.h>#define esc 27main(){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 <程序文件> -lncursesinclude <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 127static 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;}
[解决办法]
如果你不要回显,程序一开始就执行
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
因为终端的反应并不需要程序执行读终端的api,你程序while(1);时按键终端都会有反应,所以需要预先设定好
这个和windows不一样
[解决办法]
int main()
{
int key,i=1; struct termios attr;
tcgetattr( STDIN_FILENO, attr );
attr.c_lflag &= ~( ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &attr );
while(1)
{
printf("+");
sleep(1);
if (i++>=5)
{i=1;
system("clear");}
while(kbhit())
{
key=getch();
if (key==esc)
{exit (0);}
printf("%c ",key); }
}
}
[解决办法]
if(key==esc)
{
if(!kbhit()||getchar()!='[')exit(0);
}
[解决办法]