c语言通过getch()函数来使用方向键()
我参考了这篇博客,非常感谢,大家先看这篇就容易懂
先这样观察方向键的值:
#include <stdio.h>
#include <conio.h>
void main()
{
int ch ;//如果用char类型,按方向键的第一个值是-32,而不是224
while(1)//循环读取,如果不做循环的话,多用getch一次,也可以读到方向键的第二个值。
{ ch=getch();
printf("%d\n",ch);
}
}
举个例子,判断按的是不是方向键、是哪个方向键:
#include<stdio.h>
#include <conio.h>
int main()
{
int ch=0;
while (1)
{
if (getch()==224)//第一次调用getch(),如果是方向键,返回值224
{
ch=getch();//第二次调用getch()
switch (ch)
{
case 72: printf("The key you Pressed is : ↑ \n");break;
case 80: printf("The key you Pressed is : ↓ \n");break;
case 75: printf("The key you Pressed is : ← \n");break;
case 77: printf("The key you Pressed is : → \n");break;
default: printf("Unknown key \n");break;
}
}else{printf("Not direction keys \n");}
}
return 0;
}
另外写了个功能类似bioskey(0)的函数:
#define LEFT 750
#define UP 720
#define DOWN 800
#define RIGHT 770
/*这4个数字可以自行定义,我这想让它们不和常用按键混淆,所以没用小于128的数*/
int bioskey()
{
int ch=0;
ch=getch();//第一次调用getch()
if(ch==224)
{
ch=getch();//第二次调用getch()
switch (ch)
{
case 72: return UP;break;
case 80: return DOWN;break;
case 75: return LEFT;break;
case 77: return RIGHT;break;
default: break;
}
}else{return ch;}
return 0;
}
还有网上这种按键写法,把wasd这4个字母也弄成方向键:
#include "stdio.h"
void main()
{
while(1)
{ char userKey = _getch();
if (userKey == -32) // 如果是方向键就多读一次。
userKey = -_getch(); //取负数是为了不和别的按键混淆
switch (userKey)
{
case 'w':
case 'W':
case -72:
printf("up\n");
break;
case 's':
case 'S':
case -80:
printf("down\n");
break;
case 'a':
case 'A':
case -75:
printf("left\n");
break;
case 'd':
case 'D':
case -77:
printf("right\n");
break;
default:
printf("other\n");
}
}
}
最后,找了网友的答案,我觉得挺好的,你也看看: