3 回答

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
通過按一個(gè)箭頭鍵getch將三個(gè)值推入緩沖區(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貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超7個(gè)贊
如FatalError的注釋中所述,getch()函數(shù)返回兩個(gè)用于箭頭鍵(以及一些其他特殊鍵)的鍵碼。它首先返回0(0x00)或224(0xE0),然后返回一個(gè)代碼,該代碼標(biāo)識(shí)按下的鍵。
對(duì)于箭頭鍵,它首先返回224,然后返回72(向上),80(向下),75(左)和77(右)。如果按下了數(shù)字鍵盤的箭頭鍵(關(guān)閉了NumLock),getch()將首先返回0,而不是224。
請(qǐng)注意,getch()并未以任何方式標(biāo)準(zhǔn)化,并且這些代碼可能因編譯器而異。這些代碼由Windows上的MinGW和Visual C ++返回。
查看各種鍵的getch()動(dòng)作的便捷程序是:
#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()來指示它是非標(biāo)準(zhǔn)函數(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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
因此,經(jīng)過大量的奮斗,我奇跡般地解決了這個(gè)令人討厭的問題!我試圖模仿一個(gè)Linux終端,并卡在其中保留了命令歷史記錄的部分,可以通過按上下箭頭鍵進(jìn)行訪問。我發(fā)現(xiàn)ncurses lib難以理解且學(xué)習(xí)緩慢。
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
它有點(diǎn)大膽,但可以解釋很多。祝好運(yùn) !
- 3 回答
- 0 關(guān)注
- 940 瀏覽
添加回答
舉報(bào)