我正在编写一个使用getch()
扫描箭头键的程序。到目前为止我的代码是:
switch(getch()) {
case 65: // key up
break;
case 66: // key down
break;
case 67: // key right
break;
case 68: // key left
break;
}
问题是,当我按下'A'
、'B'
、'C'
或'D'
时,代码也会执行,因为65
是'A'
等的十进制代码。
有没有办法在不打电话给别人的情况下检查箭头键?
谢谢!
发布于 2012-05-07 02:59:44
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);
}
这适用于MinGW和可视化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 ... */
}
}
发布于 2013-02-14 12:00:02
所以,经过一番努力,我奇迹般地解决了这个烦人的问题!我试图模仿一个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
这有点大胆,但它解释了很多东西。祝你好运!
发布于 2017-09-07 21:10:59
有关使用带有工作代码和ncurses初始化的ncurses
的解决方案,请参见getchar() returns the same value (27) for up and down arrow keys
https://stackoverflow.com/questions/10463201
复制相似问题