0 2 Votes

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

Tutorial by Delphian | 23/12/2013 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);
begin    
  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');
end;

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;
var
  currentShiftState: TShiftState;
begin    
  currentShiftState:=GetKeyShiftState;

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

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.

ReplyPositiveNegative

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message

 

Related Topics

Delphi: System-Wide HotKey
Tutorial | 1 Comment

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.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.