C语言之控制台读取上下左右方向键指令

首先,可以检测任何按键键值

// 首先,检测任何按键的代码 
#include<stdio.h>
#include<conio.h>
int main()
{    
    char ch;
    while((ch=getch())!=0x1B) /* ESC to quit */
{
   printf("%d 
", ch);
}
 } 

分别是上下左右键的键值。

其次,控制台读取方向键指令

方法一

//捕捉键值
 #include<stdio.h>
 #include<conio.h>
 int main()
 {
 
   int ch;
   while( (ch=getch())!=0x1B ) /* Press ESC to quit... */
   {
      switch(ch)
      {
      case 0xE0:
         switch(ch=getch())
         {
            case 72:  printf("UP
"); break;
            case 80:  printf("DOWN
"); break;
            case 75:  printf("LEFT
"); break;
            case 77:  printf("RIGHT
"); break;
            default:
               break;
         }
         break;
      default:
         break;
      }
   }
}

方法二

#include <stdio.h> 
#include <stdlib.h>   
#include <conio.h>
#include <windows.h>
int main()
{
    char key;
    while(1)
    {    
    //    int t=1;
        key=getch();
        switch(key)
        {
        case -32:
            key=getch();
            switch(key)
            {
            case 72:
                printf("UP
");break;
            case 80:
                printf("DOWN
");break;
            case 75:
                printf("LEFT
");break;    
            case 77:
                printf("RIGHT
");break;
            case -123:
                                printf("F11
");break;
            case -122:
                                printf("F12
");break;
            default:
            //    printf("%x,%d,%c
",t,t,t);break;
                printf("NULL");break;
            }
            break;
            default:
            //    printf("%x,%d,%c
",t,t,t);break;
                printf("NULL");break;
        }
    }
    return 0;
}

原文地址:https://www.cnblogs.com/iloverain/p/5642753.html