程序通过修改INT 09,使之指向自己的键盘中断处理程序,来达到检测多个按键的目的。 程序来自DOS游戏编程基础,中国虚拟现实开发者(做过少量修改) 运行结果说明: 运行后按着几个按键,将在屏幕上显示其扫描码,无键被按则显示Nokey! 经试验一般可检测8个按键同时被按下! #include”dos.h” char key_state[128], key_pressed[128]; /*其中key_state[128]用来表示键的当前状态,key_pressed[128]里保存的值表示哪些键被按下,值1表示按下,0表示放开。 */ void interrupt far (*OldInt9Handler) (); /*保存好原来的键盘中断程序地址,以便在程序运行结束后恢复它*/ /*新的键盘中断程序*/ void far interrupt NewInt9 (void) { char ScanCode,temp; ScanCode = inportb (0×60); temp = inportb (0×61); outportb (0×61, temp | 0×80); outportb (0×61, temp & 0x7f); if (ScanCode & 0×80) { ScanCode &= 0x7f; key_state[ScanCode] = 0; } else { key_state[ScanCode] = 1; key_pressed[ScanCode] = 1; } outportb (0×20, 0×20); } /*安装新的键盘中断程序的函数*/ void InstallKeyboard (void) { int i; for (i = 0; i < ; 128; i++) key_state = key_pressed = 0; OldInt9Handler = getvect (9 ); setvect (9, NewInt9); } /*恢复旧的键盘中断程序的函数*/ void ShutDownKeyboard (void) { setvect (9, OldInt9Handler); } /*读取按键状态的函数*/ int GetKey (int ScanCode) { int res; res = key_state[ScanCode] | key_pressed[ScanCode]; key_pressed[ScanCode] = 0; return res; } main () { int i,press; InstallKeyboard (); while (GetKey (1)==0){ /*按ESC退出*/ press = 0; for (i = 0; i < ; 128; i++) if (GetKey (i)) { press = 1; printf (“%4d”,i); } if (press) printf (“\n”); else printf (“\nNokey!\n”); } ShutDownKeyboard (); } |
>> 本文固定链接: http://www.vcgood.com/archives/587
稍作修改使之更完善
#include”dos.h”
char key_state[128], key_pressed[128];
void interrupt far (*OldInt9Handler) ();
void far interrupt NewInt9 (void)
{
char ScanCode,temp;
ScanCode = inportb (0×60);
if (ScanCode & 0×80) {
ScanCode &= 0x7f;
key_state[ScanCode] = 0;
}
else {
key_state[ScanCode] = 1;
key_pressed[ScanCode] = 1;
}
OldInt9Handler(); /*调用原来的中断例程*/
}
void InstallKeyboard (void)
{
int i;
for (i = 0; i < 128; i++)
key_state = key_pressed = 0;
OldInt9Handler = getvect (9);
setvect (9, NewInt9);
}
void ShutDownKeyboard (void)
{
setvect (9, OldInt9Handler);
}
int GetKey (int ScanCode)
{
int res;
res = key_state[ScanCode] | key_pressed[ScanCode];
key_pressed[ScanCode] = 0;
return res;
}
main ()
{
int i,press;
InstallKeyboard ();
while (GetKey (1)==0){ /*按ESC退出*/
press = 0;
for (i = 0; i < 128; i++)
if (GetKey (i)) {
press = 1;
printf (“%4d”,i);
}
if (press)
printf (“\n”);
else
printf (“\nNokey!\n”);
}
ShutDownKeyboard ();
}