progging - To wander about and beg; to seek food or other supplies by low arts; to seek for advantage by mean shift or tricks.
progging - Programmer slang for writing computer code.

søndag 11. september 2011

Delphi: General method to check if key is pressed

To check if a specific key is pressed you can use the GetKeyState method.

  TUtility = class
    class function CheckKeyPressed(key: Integer): Boolean;
    class function ShiftKeyPressed(): Boolean;
    class function CtrlKeyPressed(): Boolean;
    class function AltKeyPressed(): Boolean;
One method can check any key you want using virtual key codes:
// Helper methods to check various key states
class function TUtility.CheckKeyPressed(key: Integer): Boolean;
  //The return value of GetKeyState specifies the status of the specified virtual key, as follows:
  //If the high-order bit is 1, the key is down; otherwise, it is up.
  //If the low-order bit is 1, the key is toggled. A key, such as the CAPS LOCK key, is toggled
  //if it is turned on.
  // The key is off and untoggled if the low-order bit is 0. A toggle key's indicator light (if any)
  // on the keyboard will be on when the key is toggled, and off when the key is untoggled.
  // Check high-order of state
  Result := (GetKeyState(key) and $80) <> 0;
...and specific methods for the most interesting keys can be made:
// Helper methods to check various key states
class function TUtility.ShiftKeyPressed(): Boolean;
  Result := CheckKeyPressed(VK_SHIFT);

class function TUtility.CtrlKeyPressed(): Boolean;
  Result := CheckKeyPressed(VK_CONTROL);

class function TUtility.AltKeyPressed(): Boolean;
  Result := CheckKeyPressed(VK_MENU);

Ingen kommentarer:

Legg inn en kommentar