在日常的应用里面,程序难免会跟用户进行互动,尤其是小游戏程序,需要实时的检测按键来判断用户的操作。那么,键盘检测如何通过代码实现呢。
下面这段代码是用来实现输入一个按键并输出对应按键ASCII码键值的程序。
#include<stdio.h>
#include<conio.h>
#include"stdafx.h"
int main(){
int key; //定义int型变量key储存键值
while (1) {
while (key = _getch()) { //检测按键并将按键键值赋给key
printf("the key you pressed is %d\n",key);
}
}
return 0;
}
但是,这个程序存在缺陷,就是没法读取四个方向键的键值,而这四个方向键在实际情况中却是应用广泛
在读取功能键和方向键的时候,要注意以下问题:
普通按键只需要读取一次ASCII码值,而功能键和方向键则需要两次,因此这种类型的检测代码是这样
#include<stdio.h>
#include<conio.h>
#include"stdafx.h"
int main(){
int key1, key2;
while (1) {
if (key1 = _getch()){
key2 = _getch();
}
switch (key2){
case 72:
printf("the key you press is up\n");
break;
case 80:
printf("the key you press is down\n");
break;
case 75:
printf("the key you press is right\n");
break;
case 77:
printf("the key you press is left\n");
break;
default:
break;
}
}
return 0;
}
附:按键键值对应图!