comment |
   This short program displays the full scan code for each key pressed 
   in ASCII/Hex notation.  Press ESC to end the program.

   Written for MASM 5.1 (should compile with earlier versions).
   Save as KEYCODE.ASM
   Compile:  MASM KEYCODE;
   	     LINK KEYCODE;
   	|
stack	segment stack
	db	100h dup (?)
stack	ends

data	segment
hextable	db	"0123456789ABCDEF"
data	ends

code	segment
	assume cs:code, ds:data, es:nothing, ss:stack
	

;---------
;  Pick the definition
;  that applies to your
;  computer
;---------
	
KEY_IN	equ	00h		;For older keyboards
;KEY_IN	equ	10h		;For "enhanced" keyboards (101/102 keys)

;---------
;  Program starts here
;---------

begin:	mov	ax,seg data	;Initialize DS
	mov	ds,ax
	call	cls		;Clear the screen
	
lp:	mov	ah,KEY_IN	;Wait for keystroke
	int	16h		;  returned by BIOS
	push	ax		;Save the key
	call	display		;Display the scan code
	pop	ax		;Recover original key
	cmp	al,01bh		;Was it ESC?
	jnz	lp		;No -- loop back
	mov	ax,4c00h	;Else exit to DOS
	int	21h

;---------
;  Simple and sloppy
;  screen-clear routine
;---------
	
cls	proc	near
	mov	ax,3		;Set mode 3 (use 7 for monochrome)
	int	10h		;Call Video BIOS
	ret
cls	endp
	
;---------
;  Display the value
;  in AX in hex notation
;  by moving each byte into AL
;  and calling print_al twice
;---------

display	proc	near		;Display AX value in hex
	push	ax		;Save keycode
	mov	ah,02		;Set cursor position
	mov	dx,0		;Top-left corner
	mov	bh,0		;Use page 0
	int	10h		;Call the video BIOS
	pop	ax		;Recover original keycode

disp_2:	push	ax		;Save keycode again
	mov	al,ah		;Move high byte into AL
	call	print_al	;Print value in AL
	pop	ax		;Recover keycode
	call	print_al	;Print low byte
	ret
display	endp

;---------
;  Display the value in AL
;  in hex format
;---------

print_al proc	near
	mov	bx,offset hextable  ;DS:BX ==> translation table
	cbw			;AH = 0
	push	ax		;Save the byte
	mov	cl,4		;Shift top nibble in AL
	shr	al,cl		;  to the bottom
	xlat			;Get hex character
	mov	ah,0eh		;Video service: print TTY mode
	int	10h		;Print the character
	pop	ax		;Recover the byte
	and	al,0fh		;Mask out high nibble
	xlat			;Translate low nibble to hex
	mov	ah,0eh		;And print it
	int	10h		;  with a BIOS call
	mov	al,' '		;Now print a space
	int	10h		;  with a BIOS call
	ret
print_al endp

code	ends
	end	begin
