qwe*_*rtz 40 c character decimal getch arrow-keys
我正在编写一个getch()用于扫描箭头键的程序.到目前为止我的代码是:
switch(getch()) {
case 65: // key up
break;
case 66: // key down
break;
case 67: // key right
break;
case 68: // key left
break;
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我按下'A','B','C'或'D'代码也将执行,因为65是十进制代码'A',等等.
有没有办法检查箭头键而不打电话给别人?
谢谢!
qwe*_*rtz 61
按下一个箭头键getch将三个值推入缓冲区:
'\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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 19
getch()函数返回箭头键(和其他一些特殊键)的两个键码,如FatalError的注释中所述.它首先返回0(0x00)或224(0xE0),然后返回一个代码,用于标识按下的键.
对于箭头键,它首先返回224,然后是72(向上),80(向下),75(向左)和77(向右).如果按下数字键盘箭头键(关闭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);
}
Run Code Online (Sandbox Code Playgroud)
这适用于MinGW和Visual C++.这些编译器使用名称_getch()而不是getch()来表示它是非标准函数.
所以,你可以这样做:
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 ... */
}
}
Run Code Online (Sandbox Code Playgroud)
所以,经过一番挣扎,我奇迹般地解决了这个烦人的问题!我试图模仿一个 linux 终端并被卡在它保留命令历史记录的部分,可以通过按向上或向下箭头键来访问它。我发现 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
Run Code Online (Sandbox Code Playgroud)
这有点大胆,但它解释了很多。祝你好运 !