Code:
#define KEYBDINT 0x09
#define CTRLBREAKINT 0x23
interrupt (*OldKeyHandler)(...)=0;
char keys[128];
//Installs KeyHandler on int 09h
void InstallKeyHandler(void);
//Removes/restores keyboard int 09h
void UninstallKeyHandler(void);
//Uninstalls all vectors for this process
void UninstallVectors(void);
//Installs all vectors for this process
void InstallVectors(void);
interrupt MyKeyboardHandler(...)
{
int key=inp(0x60);
if (key>128) //0x80
{
keys[key-128]=0;
} else keys[key]=1;
//Don't call the old handler
}
interrupt CtrlBreakHandler(...)
{
UninstallVectors(); //Restor vector table
exit(0); //exit
//no need to restore int 23h vector, DOS will do this
}
void InstallKeyHandler(void)
{
//DOS Way to install vector
OldKeyHandler=getvect(KEYBDINT);
setvect(KEYBDINT,MyKeyboardHandler);
}
void UninstallKeyHandler(void)
{
setvect(KEYBDINT,OldKeyHandler);
}
void InstallBreakHandler(void)
{
setvect(CTRLBREAKINT,BreakHandler);
}
void UninstallVectors(void)
{
UninstallKeyHandler();
//Any other vectors that need to be restored go here
}
void InstallVectors(void)
{
InstallBreakHandler();
InstallKeyHandler();
//any other handlers needing to be installed go here
}
Note that you do not have to explicitly restore the CTRL BREAK handler or the handler for INT 23h. DOS will do this for you. The main reason for the functions that install and uninstall the vectors is so that you can install all vectors and uninstall all vectors with one call. This is very handy for debugging because when you press CTRL BREAK, the vector table will be restored to its original state and you will be able to continue. You should also put in an atexit() function so that when exit(returncode) is issued, it will call atexit() which will call UninstallVectors. This will ensure that you will be able to write interrupt handlers, test them, and the system will remain stable.
To use this code:
if keys[scancode]
{
..key is pressed
} else ..key is not pressed