Microsoft KB Archive/57441

From BetaArchive Wiki
Knowledge Base

Macintosh QuickBASIC ToolBox Call to Trap Any Key Press

Article ID: 57441

Article Last Modified on 11/21/2006

This article was previously published under Q57441


The following program shows how key presses can be trapped by polling values returned from a ToolBox call in a loop. This technique can be used to check if any key on the keyboard is currently being pressed, such as the function keys on the extended keyboard and the TAB key. You can also check if the COMMAND key, OPTION key, or a SHIFT key is currently down.

This information applies to Microsoft QuickBASIC Version 1.00 for the Apple Macintosh.


A ToolBox call can be made to the GetKeys function, which returns a sequence of bits that shows the current status of all the keys on the keyboard. The bit position for a particular key is determined by the key code for that key on the keyboard. The key codes are defined in Apple's "Inside Macintosh" Volume I (Addison-Wesley, 1985), Page I-251, and Apple's "Inside Macintosh" Volume V (Addison-Wesley, 1986), Page V-192. Some sample key codes are as follows:

   F1 = 122   F2 = 120   F3 = 99   PgDn = 121

The following program prompts you to enter the key code of the key whose status you wish to poll. The program will then sit in a loop displaying the status of that key until the ESC (escape) key is pressed. A status of 0 indicates that the key is not currently pressed, while a status of -1 indicates a key press:

DIM SHARED KeyArray(8)
Toolbox "i"
PRINT "Your Choices are: ";
PRINT " F1 = 122   F2 = 120   F3 = 99  or Page Down = 121 "
INPUT "Key-Code to test for: "; KeyCode
PRINT "Press ESC to exit"
PRINT "Keyboard State (-1 = Key is currently pressed)"
PRINT "----------------------------------------------"
WHILE INKEY$ <> CHR$(27)   ' Check for escape key
   CALL TestKey(KeyCode, status)
   LOCATE 4, 1
   PRINT "Key "; KeyCode; " "; status

SUB TestKey(KeyCode, status) STATIC
   ' Subroutine to determine if a give key is currently being
   ' pressed.  Called with:
   '   KeyCode = key code as defined in Inside Macintosh
   '   status = BOOLEAN returned value (-1 = key pressed,
   '                                     0 = not pressed)
   Toolbox "PQ", &HA976, KeyArray(0)  ' Call GetKeys toolbox routine
   ArrayLoc = KeyCode \ 8             ' Memory offset in array
   Bit = KeyCode - (ArrayLoc * 8)     ' Bit to check
   ArrayElement = PEEK(VARPTR(KeyArray(0)) + ArrayLoc)
   status = (ArrayElement AND 2^Bit) = 2^Bit

Additional query words: MQuickB

Keywords: KB57441