首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >getch和箭头代码

getch和箭头代码
EN

Stack Overflow用户
提问于 2012-05-05 23:18:39
回答 8查看 143.6K关注 0票数 46

我正在编写一个使用getch()扫描箭头键的程序。到目前为止我的代码是:

代码语言:javascript
运行
复制
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'等的十进制代码。

有没有办法在不打电话给别人的情况下检查箭头键?

谢谢!

EN

回答 8

Stack Overflow用户

发布于 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 ()对各种键的操作,一个方便的程序是:

代码语言:javascript
运行
复制
#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 ()来表示它是一个非标准函数。

所以,你可以这样做:

代码语言:javascript
运行
复制
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 ... */
    }
}
票数 24
EN

Stack Overflow用户

发布于 2013-02-14 12:00:02

所以,经过一番努力,我奇迹般地解决了这个烦人的问题!我试图模仿一个linux终端,但在它保存命令历史的部分卡住了,可以通过按向上或向下箭头键来访问。我发现ncurses lib很难理解,学习起来也很慢。

代码语言:javascript
运行
复制
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

这有点大胆,但它解释了很多东西。祝你好运!

票数 5
EN

Stack Overflow用户

发布于 2017-09-07 21:10:59

有关使用带有工作代码和ncurses初始化的ncurses的解决方案,请参见getchar() returns the same value (27) for up and down arrow keys

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10463201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档