我正在编写一个使用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-07-11 20:26:29
按下一个箭头键,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;
}
}发布于 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这有点大胆,但它解释了很多东西。祝你好运!
https://stackoverflow.com/questions/10463201
复制相似问题