GetKeyState 函数

GetKeyState 函数返回用户所按下按键的代码。

参数: 函数不接受参数。

返回值: AX:所按键的代码。

标志状态: 函数影响所有标志。

程序源代码(示例 1:等待 ALT+F4)

Intel 8086 汇编程序示例,演示使用 GetKeyState 函数获取所按键的代码。

title Author: Dovgopolov Evgeny Sergeevich

.model small
.stack 100h

data segment public
    string db "Press ALT+F4 to exit the program...\n\0"
data ends

code segment public               ; 代码段开始
    assume  ds:data, cs:code
    include Handyfar.inc          ; 包含函数文件
    include Handykey.inc          ; 包含键盘按键值文件

    main proc                     ; main 过程开始
        call    SetDataSegment    ; 调用过程 SetDataSegment

        lea     ax, ds:[string]   ; 将变量 string 的地址装入寄存器 ds:ax
        call    WriteString       ; 调用过程 WriteString(ax:string)

    WaitUserKeyPress:
        call    GetKeyState       ; 调用过程 GetKeyState() := AX
        cmp     ax, KB_ALT_F4     ; 将用户输入的值与 KB_ALT_F4 进行比较
        jne     WaitUserKeyPress  ; 如果 ZF=0,则跳转到标号 WaitUserKeyPress

        xor     al, al            ; 清零寄存器 al
        call    ExitProcess       ; 调用过程 ExitProcess
    main endp                     ; main 过程结束

code ends                         ; 代码段结束
end main	                      ; 文件结束。入口点指定为过程 main

(程序等待按下 ALT+F4,然后结束)

程序源代码(示例 2:按空格键循环移位)

title Author: Dovgopolov Evgeny Sergeevich

.model small
.stack 100h

data segment public
    fmtout db "%b\n\0"
    number dw 0001000110100101b
data ends

code segment public                ; 代码段开始
    assume  ds:data, cs:code
    include Handyfar.inc           ; 包含函数文件
    include Handykey.inc           ; 包含键盘按键值文件

    main proc                      ; main 过程开始
        call    SetDataSegment     ; 调用过程 SetDataSegment

        mov     cx, 16             ; 将计数器设为 16

    MainLoop:
        push    cx                 ; 将计数器的值保存到栈中

        push    number             ; 第2步:保存变量 number 的值
        lea     ax, ds:[fmtout]    ; 第1步:将格式字符串 fmtout 装入寄存器 ds:ax
        call    PrintFormatString  ; 调用过程 PrintFormatString(ax:fmtout, number)
        add     sp, 2              ; 对齐栈

        call    GetKeyState        ; 调用过程 GetKeyState() := AX
        cmp     ax, KB_SPACE       ; 将用户输入的值与 KB_SPACE 进行比较
        jne     Done               ; 如果 ZF=0,则跳转到标号 Done

        rol     number, 1          ; 将各位循环左移 1 位
        pop     cx                 ; 将计数器的值从栈中弹回寄存器 cx
        loop    MainLoop           ; 当 ZF≠0 或 CX≠0 时执行循环

    Done:
        xor     al, al             ; 清零寄存器 al
        call    ExitProcess        ; 调用过程 ExitProcess
    main endp                      ; main 过程结束

code ends                          ; 代码段结束
end main	                       ; 文件结束。入口点指定为过程 main

0001 0001 1010 0101
0010 0011 0100 1010
0100 0110 1001 0100
1000 1101 0010 1000
...

示例取自教材 "HANDYFAR - MASM (Dovgopolov Evgeny Sergeevich)".