The GetKeyState function
The GetKeyState function returns the code of the key pressed by the user.
Parameters: The function takes no parameters.
Return value: AX: the code of the pressed key.
Flag state: The function affects all flags.
Program source code (Example 1: waiting for ALT+F4)
An example program for the Intel 8086 assembler demonstrating the use of the GetKeyState function to obtain the code of the pressed key.
title .model small .stack 100h data segment public string db "Press ALT+F4 to exit the program...\n\0" data ends code segment public ; Start of the code segment assume ds:data, cs:code include Handyfar.inc ; Include the file with functions include Handykey.inc ; Include the file with the keyboard key values main proc ; Start of the main procedure call SetDataSegment ; Call the SetDataSegment procedure lea ax, ds:[string] ; Load the address of the string variable into the ds:ax register call WriteString ; Call the WriteString procedure (ax:string) WaitUserKeyPress: call GetKeyState ; Call the GetKeyState procedure () := AX cmp ax, KB_ALT_F4 ; Compare the value entered by the user with KB_ALT_F4 jne WaitUserKeyPress ; If ZF=0, jump to the label WaitUserKeyPress xor al, al ; Clear the al register call ExitProcess ; Call the ExitProcess procedure main endp ; End of the main procedure code ends ; End of the code segment end main ; End of file. The main procedure is the entry point
(The program waits for ALT+F4 to be pressed, then exits)
Program source code (Example 2: bit rotation on space)
title .model small .stack 100h data segment public fmtout db "%b\n\0" number dw 0001000110100101b data ends code segment public ; Start of the code segment assume ds:data, cs:code include Handyfar.inc ; Include the file with functions include Handykey.inc ; Include the file with the keyboard key values main proc ; Start of the main procedure call SetDataSegment ; Call the SetDataSegment procedure mov cx, 16 ; Set the counter to 16 MainLoop: push cx ; Save the counter value on the stack push number ; 2nd: Save the value of the number variable lea ax, ds:[fmtout] ; 1st: Load the fmtout format string into the ds:ax register call PrintFormatString ; Call the PrintFormatString procedure (ax:fmtout, number) add sp, 2 ; Align the stack call GetKeyState ; Call the GetKeyState procedure () := AX cmp ax, KB_SPACE ; Compare the value entered by the user with KB_SPACE jne Done ; If ZF=0, jump to the label Done rol number, 1 ; Rotate the bits left by 1 pop cx ; Pop the counter value from the stack back into the cx register loop MainLoop ; Loop while ZF≠0 or CX≠0 Done: xor al, al ; Clear the al register call ExitProcess ; Call the ExitProcess procedure main endp ; End of the main procedure code ends ; End of the code segment end main ; End of file. The main procedure is the entry point
0001 0001 1010 0101
0010 0011 0100 1010
0100 0110 1001 0100
1000 1101 0010 1000
...
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".