Blitz3D+ Command Reference

GetKey ( )

Parameters

None.

Description

Takes the next character the player typed out of the keyboard queue.

Where KeyDown and KeyHit deal in scan codes for game controls, GetKey deals in characters. It respects the keyboard layout and the shift state, so pressing Shift and A really does give you a capital A. That makes it the command for text: entering a high-score name, a chat line, a debug console, a rename box.

Keys are queued as they are pressed, and every call removes one and returns its ASCII code. When the queue is empty it returns 0, so the usual pattern is to drain it each frame with a Repeat loop that keeps calling GetKey until it hands back a zero. Because it is a queue rather than a live state, no keystroke is lost between frames even if you only call it once per loop.

Keys that have no character - Shift, Ctrl, Alt, the function keys - are still pulled off the queue but return 0, so they quietly disappear. The navigation cluster returns small control codes instead of ASCII: Home 1, End 2, Insert 3, Delete 4, Page Up 5, Page Down 6, Up 28, Down 29, Right 30, Left 31. The ordinary control characters come through as themselves: Backspace 8, Tab 9, Enter 13, Escape 27.

FlushKeys empties the queue, which is worth doing before you open a text box so earlier gameplay keys do not appear in it. If you want a whole line typed, with a cursor and the editing keys already handled for you, use Input rather than writing your own editor around GetKey.

See also: WaitKey, KeyHit, KeyDown, FlushKeys, Input, ScanCodes.

Example

; GetKey Example
; --------------

Graphics 640,480,0,2
SetBuffer BackBuffer()

typed$=""
last_key=0

While Not KeyDown(1)

    Cls

    ; GetKey returns the ASCII code of the next key waiting in the
    ; keyboard buffer, or 0 if no key has been pressed.
    k=GetKey()
    If k>0 Then last_key=k

    ; Printable characters (ASCII 32..126) build a typing preview
    If k>=32 And k<=126 Then typed$=typed$+Chr$(k)

    ; Backspace (ASCII 8) deletes the last character
    If k=8 And Len(typed$)>0 Then typed$=Left$(typed$,Len(typed$)-1)

    Text 0,0,"Type something   Backspace: delete   Esc: exit"
    If last_key=0 Then
        Text 0,20,"Waiting for the first key..."
    Else
        Text 0,20,"Last GetKey() code: "+last_key
    End If
    If last_key>=32 And last_key<=126 Then Text 0,40,"That is the character '"+Chr$(last_key)+"'"

    Text 0,80,"You typed: "+typed$+"_"

    Flip

Wend

End

Index