为了账号安全,请及时绑定邮箱和手机立即绑定

密码和箭头代码

密码和箭头代码

C
元芳怎么了 2019-10-18 15:08:54
我正在编写一个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',等等。有没有一种方法可以在不呼叫他人的情况下检查箭头键?谢谢!
查看完整描述

3 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

通过按一个箭头键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;

    }

}


查看完整回答
反对 回复 2019-10-18
?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

如FatalError的注释中所述,getch()函数返回两个用于箭头键(以及一些其他特殊键)的键码。它首先返回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和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 ... */

    }

}


查看完整回答
反对 回复 2019-10-18
?
弑天下

TA贡献1818条经验 获得超7个赞

因此,经过大量的奋斗,我奇迹般地解决了这个令人讨厌的问题!我试图模仿一个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

它有点大胆,但可以解释很多。祝好运 !


查看完整回答
反对 回复 2019-10-18
  • 3 回答
  • 0 关注
  • 824 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信