2011-07-14 85 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