QBasic / QB64 Discussion Forum      Other Subforums, Links and Downloads
 Return to Index  

How to test the keyboard, including F-keys and arrow keys

January 13 2004 at 9:59 AM
  (Login Mac36)

FAQ017 = How can I test the keyboard, including F-keys and arrow keys?

In response to K$ = INKEY$, there are three possibilities:

---> LEN(K$) = 0

This means no key has been pressed. The usual way to read the keyboard is
DO: K$ = INKEY$: LOOP WHILE K$ = ""
which will only drop out when a key is pressed.

To clear the keyboard buffer, use
WHILE INKEY$ = "": WEND

---> LEN(K$) = 1

This is for normal keys such as a-z, Enter, Esc, etc.

For a list of the key codes that may be returned:
- Go to QBasic HELP
- Chose Quick Reference item ASCII Character Codes
This shows, for example, that the code for Enter, called carriage return (cr) is 13.

To test for Enter (carriage return),
IF K$ = CHR$(13) THEN ...

But most keys are simply tested like this:
IF UCASE$(K$) = "A" THEN ...
(The UCASE$ is used if you want "A" and "a" and don't care which.

---> LEN(K$) = 2

This is for arrow keys, F-keys, etc.

For an explanation,
- Go to QBasic HELP
- Chose INKEY$ Function
- After reading, chose "Keyboard Scan Codes" for details

Having read this, you will understand that to test for F1
IF K$ = CHR$(0) + CHR$(59) THEN ... (you have found F1)

Many programmers avoid the scan codes for the arrow codes by memorizing the letters HPKM as arrow keys up/down/left/right so instead of
IF K$ = CHR$(0) + CHR$(77) THEN ... (you have found Right Arrow)
they code
IF K$ = CHR$(0) + "M" THEN ... (you have found Right Arrow)
or else they make self-documenting constants
RightArrow$ = CHR$(0) + "M"
and then test like this
IF K$ = RightArrow$ THEN ... (you have found Right Arrow)

Below is a program that will show the codes in case you don't want to look them up.

Mac

CLS
PRINT "Press keys to see what to test for"
PRINT "(Press ESC when finished)"
DO
  PRINT
  LOCATE , , 1: PRINT "Key: ";
  DO: k$ = INKEY$: LOOP WHILE k$ = ""
  GOSUB GetASC
  IF LEN(k$) = 1 THEN
    PRINT a$; more$
  ELSE
    PRINT "ASC(0)+"; a$; more$
  END IF
LOOP WHILE k$ <> CHR$(27)
SYSTEM
GetASC:
a = ASC(RIGHT$(k$, 1))
a$ = "ASC(" + LTRIM$(STR$(a)) + ")"
IF a < 32 THEN
  more$ = ""
ELSE
  more$ = " or " + CHR$(34) + RIGHT$(k$, 1) + CHR$(34)
END IF
RETURN

 
 Respond to this message