3 回答

TA貢獻1812條經(jīng)驗 獲得超5個贊
通過按一個箭頭鍵getch將三個值推入緩沖區(qū):
'\033'
'['
'A','B','C'或者'D'
因此,代碼將如下所示:
if (getch() == '\033') { // if the first value is esc
getch(); // skip the [
switch(getch()) { // the real value
case 'A':
// code for arrow up
break;
case 'B':
// code for arrow down
break;
case 'C':
// code for arrow right
break;
case 'D':
// code for arrow left
break;
}
}

TA貢獻1794條經(jīng)驗 獲得超8個贊
如FatalError的注釋中所述,getch()函數(shù)返回兩個用于箭頭鍵(以及一些其他特殊鍵)的鍵碼。它首先返回0(0x00)或224(0xE0),然后返回一個代碼,該代碼標識按下的鍵。
對于箭頭鍵,它首先返回224,然后返回72(向上),80(向下),75(左)和77(右)。如果按下了數(shù)字鍵盤的箭頭鍵(關(guān)閉了NumLock),getch()將首先返回0,而不是224。
請注意,getch()并未以任何方式標準化,并且這些代碼可能因編譯器而異。這些代碼由Windows上的MinGW和Visual C ++返回。
查看各種鍵的getch()動作的便捷程序是:
#include <stdio.h>
#include <conio.h>
int main ()
{
int ch;
while ((ch = _getch()) != 27) /* 27 = Esc key */
{
printf("%d", ch);
if (ch == 0 || ch == 224)
printf (", %d", _getch ());
printf("\n");
}
printf("ESC %d\n", ch);
return (0);
}
這適用于MinGW和Visual C ++。這些編譯器使用名稱_getch()而不是getch()來指示它是非標準函數(shù)。
因此,您可以執(zhí)行以下操作:
ch = _getch ();
if (ch == 0 || ch == 224)
{
switch (_getch ())
{
case 72:
/* Code for up arrow handling */
break;
case 80:
/* Code for down arrow handling */
break;
/* ... etc ... */
}
}

TA貢獻1818條經(jīng)驗 獲得超8個贊
因此,經(jīng)過大量的奮斗,我奇跡般地解決了這個令人討厭的問題!我試圖模仿一個Linux終端,并卡在其中保留了命令歷史記錄的部分,可以通過按上下箭頭鍵進行訪問。我發(fā)現(xiàn)ncurses lib難以理解且學習緩慢。
char ch = 0, k = 0;
while(1)
{
ch = getch();
if(ch == 27) // if ch is the escape sequence with num code 27, k turns 1 to signal the next
k = 1;
if(ch == 91 && k == 1) // if the previous char was 27, and the current 91, k turns 2 for further use
k = 2;
if(ch == 65 && k == 2) // finally, if the last char of the sequence matches, you've got a key !
printf("You pressed the up arrow key !!\n");
if(ch == 66 && k == 2)
printf("You pressed the down arrow key !!\n");
if(ch != 27 && ch != 91) // if ch isn't either of the two, the key pressed isn't up/down so reset k
k = 0;
printf("%c - %d", ch, ch); // prints out the char and it's int code
它有點大膽,但可以解釋很多。祝好運 !
- 3 回答
- 0 關(guān)注
- 953 瀏覽
添加回答
舉報