KEYPRESS function

Purpose:

KEYPRESS returns a value corresponding to the key combination pressed. KEYPRESS waits for keyboard input but does not automatically echo to the screen.

👉 Because the KEYPRESS function uses device-dependent values generated by the keyboard hardware/software for return of some of the key presses, consistent values cannot be assured across various hardware/software configurations.

Also, on some systems, because mouse and keyboard handlers are tied together in Windows, KEYPRESS will return values when the mouse is moving over an active window.

Syntax 1:

RetVal = KEYPRESS

Return Value:

  • Data type: INTEGER
    RetVal
    • Alphanumeric keys return the Windows Code Page code point value of the character corresponding to the key pressed.
    • Ctrl + alpha keys return (ASCIIcode - 96).
    • Alt + alphanumeric keys return (Scancode + 1000).
    • Alt + enhanced keys return (Scancode + 1000) * -1.
    • Ctrl + enhanced keys return (Scancode + 2000) * -1.
    • The Extended keys listed below, typically, return
       BackSpace :   8
       Home      : -71
       End       : -79
       PageUp    : -73
       PageDown  : -81
       Insert    : -82
       Delete    : -83
      
      Cursor keys:
       Up        : -72
       Down      : -80
       Left      : -75
       Right     : -77
      
      Function keys:
       F1        : -59
       F2        : -60
       F3        : -61
       F4        : -62
       F5        : -63
       F6        : -64
       F7        : -65
       F8        : -66
       F9        : -67
       F10       : -68
      

    Parameters:

    • None.
DIM a

PRINT "Press keys to see their key codes .. Press q to quit"

WHILE a <> ASC("q")
  a = KEYPRESS
  PRINT a
WEND

The GUI snippet below shows another way to capture a keypress.

GUI "GetKey"

SUB FORMLOAD
  GLOBAL Form1 AS HWND
  Form1 = BCX_FORM("GetKey", 0, 0, 110, 110)
  BCX_SET_FORM_COLOR(Form1,QBCOLOR(31))
  CENTER(Form1)
  SHOW(Form1)
END SUB

BEGIN EVENTS
  SELECT CASE CBMSG
  CASE WM_GETDLGCODE
    FUNCTION=DLGC_WANTALLKEYS
  CASE WM_KEYDOWN
    SELECT CASE wParam
    CASE VK_HOME
      MSGBOX "VK_HOME"
    CASE VK_END
      MSGBOX "VK_END"
    CASE VK_NEXT
      MSGBOX "VK_NEXT"
    CASE VK_PRIOR
      MSGBOX "VK_PRIOR"
    CASE VK_DOWN
      MSGBOX "VK_DOWN"
    CASE VK_UP
      MSGBOX "VK_UP"
    CASE VK_LEFT
      MSGBOX "VK_LEFT"
    CASE VK_RIGHT
      MSGBOX "VK_RIGHT"
    CASE VK_RETURN
      MSGBOX "VK_RETURN"
    END SELECT
  END SELECT
END EVENTS

BCX Console Sample Programs using the KEYPRESS function.