WAITKEY$ function

Purpose

Read a character or mouse event from the console input buffer, without echoing the character to the screen.  If no event is available, WAITKEY$ will wait for an event to arrive in the console input buffer.

Syntax

As a function:

i$ = WAITKEY$

As a statement:

WAITKEY$

Remarks

While waiting, time-slices for the current thread are released back to the operating system, in order to reduce CPU load.

WAITKEY$ returns a string of one or two characters that reflects the status of the keyboard buffer.  It can also return a string of four bytes if mouse event trapping is enabled.  WAITKEY$ will always read keys from the keyboard, regardless of STDIN redirection status.

A string length of one (LEN(i$) = 1) means that an ASCII key was pressed, and the string contains the ASCII character (values between 1 and 31 indicate a control code).

A string length of two (LEN(i$) = 2) means that an extended key was pressed.  In this case, the first character in the string has a value of zero, and the second is the extended keyboard code.  For example, pressing the F1 key will return CHR$(0, 59).

A string length of four (LEN(i$) = 4) means that a mouse event was retrieved.  In this case, the first two characters in the string have a value of 255.  The third character is an event code:

Value

Definition

1

movement

2

double-click

4

button press

8

button release

 

The fourth character defines the button that was pressed:

Value

Definition

0

no button

1

left

2

right

4

second left button

8

third left button

16

fourth left button

 

For example, moving the mouse with the left button pressed will return CHR$(255, 255, 1, 1).  Button presses can be combined, for example pressing the left and right mouse buttons together will return CHR$(255, 255, 4, 3).  The Mouse must be enabled with the MOUSE statement in order to receive mouse events.

WAITKEY$ used as a statement will simply remove a key from the keyboard event.  If no key is present, it will wait for the next keyboard event.

See also

ASC, INPUT FLUSH, INKEY$, INSHIFT, INSTAT, LINE INPUT, MOUSE, MOUSESTAT, MOUSEX, MOUSEY, WAITSTAT

Example

FUNCTION PBMAIN() AS LONG

  PRINT "Display all CHR$ codes for keyboard and mouse events"

  PRINT "Press 'q' to Quit"

  PRINT

  PRINT "CHR     WAITKEY$ ="

  ' Make the caret visible. Turn mouse events ON,

  ' and set to trap all mouse events

  CURSOR ON

  MOUSE ON

  MOUSE 3, DOUBLE, MOVE, DOWN, UP

  DO

    i$ = WAITKEY$  ' Wait for a key or mouse event

    IF LEN(i$) = 1 THEN

      PRINT " "; i$; "      CHR$("; ASC(i$); ")"

      IF i$ = "q" THEN EXIT DO

    ELSEIF LEN(i$) = 2 THEN

      PRINT "        CHR$(0,"; ASC(i$, 2); ")"

    ELSEIF LEN(i$) = 4 THEN

      PRINT "Mouse   CHR$(255,255,"; _

        ASC(i$, 3); ","; ASC(i$, 4); ")"

    END IF

  LOOP

END FUNCTION