Notice Of Closure

Please note that this website is due to close down on 15th June 2020.

In the interim I will try to move as much content as possible over to my GitHub account. Thanks to everyone who has supported the site over the years.

» Help

How to check if a key is pressed

   

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;
begin
  Result := GetKeyState(VK_CONTROL) < 0;
end;
See also the IsKeyPressed routine in the Code Snippets Database.
Author: Peter Johnson
Contributor: Peter Johnson
Added: 2007-07-04
Last updated: 2013-10-12

« Return to contents »