13 Votes

Delphi/Lazarus: Is the ALT, SHIFT or CTRL key pressed?

Tutorial by Delphian | 2013-12-23 at 19:44

Sometimes, we want to check at an arbitrary point in our program, if the user just holds down the keys ALT, ALT GR, SHIFT or CTRL. To put this in experience, TShiftState is helping us.

ShiftState in Standard-Events

The easiest way to use it is to use it in a standard procedure in Delphi or Lazarus, which already provides us a variable of TShiftState. This is the case, for example, in the default events OnMouseDown (mouse button is pressed), OnMouseUp (mouse is released) or OnKeyUp (key is released). Let's look at a short example:

procedure Edit1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
  if ssAlt in Shift then ShowMessage('ALT');
  if ssShift in Shift then ShowMessage('SHIFT');
  if ssCtrl in Shift then ShowMessage('STRG');
  if ssAltGr in Shift then ShowMessage('ALT GR');
  if ssLeft in Shift then ShowMessage('Left Mouse Key');
  if ssRight in Shift then ShowMessage('Right Mouse Key');
  if ssMiddle in Shift then ShowMessage('Middle Mouse Key');
  if ssDoubleClick in Shift then ShowMessage('Double Click');

Here, for example, we have set the OnKeyUp event for an edit field. Automatically, the variables Key and Shift are available from which we can retrieve which normal key is pressed (Key variable) and which special key was pressed during pressing the key (Shift variable).

Next to find out whether the user is holding the ALT, SHIFT, CTRL or ALT GR key, using Shift State it is also possible to get information about the mouse (is the right or left mouse button pressed or is there a double click, for example).

ShiftState in an own Procedure

When writing our own procedure or function, of course, Delphi or Lazarus does not automatically make the variable Shift available. Nevertheless, it is possible to retrieve the current shift state.

procedure MyOwnProcedure;
  currentShiftState: TShiftState;

  if ssShift in currentShiftState then ShowMessage('SHIFT');

We just declare a variable of the type TShiftState. Let's call it currentShiftState. With the GetKeyShiftState function, we can request the current shift state and store it in our variable. After that we can just work with it like we have done it in the first example.


About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.