How to check if a key is pressed #45

Use the Windows GetKeyState function to get data about the required key. GetKeyState can be passed either a virtual key code such as VK_CONTROL or an ascii value such as Ord('A').

The data returned by GetKeyState has its high bit set if the key is pressed, making the returned (signed) value negative. So to check if a key is down we simply check for a negative return value from GetKeyState. Here's a function that checks if the Control key is presssed:

function IsControlKeyPressed: Boolean;
  Result := GetKeyState(VK_CONTROL) < 0;
See also the IsKeyPressed routine in the DelphiDabbler Code Snippets Database.
Author: Peter Johnson
Contributor: Peter Johnson
Added: 2007/07/04
Last updated: 2013/10/12