2011-07-14 103 views
3
充分利用控制台原始输入
/* Initialize new terminal i/o settings */ 
static struct termios old, new1; 
void initTermios(int echo) { 
    tcgetattr(0, &old); /* grab old terminal i/o settings */ 
    new1 = old; /* make new settings same as old settings */ 
    new1.c_lflag &= ~ICANON; /* disable buffered i/o */ 
    new1.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */ 
    tcsetattr(0, TCSANOW, &new1); /* use these new terminal i/o settings now */ 
} 

/* Restore old terminal i/o settings */ 
void resetTermios(void) { 
    tcsetattr(0, TCSANOW, &old); 
} 

我怎样才能得到箭头键输入(可能为单个字符),目前的代码工作好所有其他的事情,我需要......请无解ncurses的使用C或C++

+1

'new1.c_lflag&=回波? ECHO:〜ECHO'这真的有用吗?我认为它应该更多地沿着'new1.c_lflag = echo? new1.c_lflag | ECHO:new1.c_lflag&〜ECHO' – Fiktik

+0

它完美的作品给它一个镜头 – Shawn

+0

@Shawn:Fiktik是完全正确,看起来像只关闭回声和从来没有测试将其打开。 –

回答

3

您是否尝试过read功能?

这对我的作品与cygwin的G ++,没有linux的方便测试:

#include <unistd.h> 
#include <termios.h> 
#include <stdio.h> 

/* Initialize new terminal i/o settings */ 
static struct termios old, new1; 
void initTermios(int echo) { 
    tcgetattr(0, &old); /* grab old terminal i/o settings */ 
    new1 = old; /* make new settings same as old settings */ 
    new1.c_lflag &= ~ICANON; /* disable buffered i/o */ 
    new1.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */ 
    tcsetattr(0, TCSANOW, &new1); /* use these new terminal i/o settings now */ 
} 

/* Restore old terminal i/o settings */ 
void resetTermios(void) { 
    tcsetattr(0, TCSANOW, &old); 
} 

int main(void) 
{ 
    char c; 
    initTermios(0); 
    while (1) { read(0, &c, 1); printf("%d\n", c); } 
} 

由于@Fiktik指出,回声设置坏了,但我使用没有问题的代码变化。

+0

@duskwuff:你有没有注意到他已经关闭了规范(熟)模式? –

5

你不能做到这一点在标准C++/C,你需要非标准CONIO.H文件和残培()扩展。然后,你可以调用函数getch()两次拿到钥匙代码为箭头

#include <conio.h> 
using namespace std; 

int main() 
{ 
    cout << "press up arrow;" << endl; 
    int control = getch(); //gets the escape character 
    int keycode = getch(); //gets the code 
    cout << control << endl; 
    cout << keycode << endl; 
} 
+0

谢谢,但conio.h在linux中不受支持。 =( – Shawn

1

为单个字符,这是不可能的(输入的字符序列)。 可以通过实现自己的输入功能使它看起来像单个字符。喜欢的东西:

struct key_data { 
    enum key_type kt; /* ARROW, FUNCTION, REGULAR, etc */ 
    unsigned char key; /* depends on kt */ 
}; 

int get_key_press (struct key_data * kd) { 
    int c = getc(stdin); 
    switch (c) { 
     /* 
     If c is a control character, process further characters to see what needs to happen 
     */ 
    } 
    return 0; 
} 

/* later, in main */ 
    struct key_data kd; 
    get_key_press (&kd); 
    if (kd.kt == ARROW_KEY) { 
     switch (kd.key) { 
     case ARROW_RIGHT: 
      printf("Right Arrow Pressed\n"); 
      break; 
     /* and so on */ 

所以实施,您可以使用get_key_press表现得像是越来越单个字符之后。

虽然这项工作是为你在其他地方已经完成;为什么厌恶ncurses