00 Votes

Lazarus: CMD-Key in OnKeyDown Event on Mac OS X

Question by Guest | 2017-03-26 at 23:09

For lots of actions for which you would use the CTRL key on Windows, the CMD key is used on Mac OS X.

In one of my Lazarus applications, up to now I have used something like "if ((ssCtrl in Shift) and (Key = 65)) then ..." in an OnKeyDown event (see using CTRL+A for selecting all for more details about that implementation).

However, how can I adjust this for Apple Mac OS X that it is working with the CMD key instead of CTRL? Is there something like ssCtrl for CMD? Unfortunately, there seems to be no ssCMD constant for that...

ReplyPositiveNegative
Avatar
1Best Answer1 Vote

Instead of using ssCtrl, you can use the ShiftState ssMeta on Mac OS X . ssMeta is standing for the CMD key.

With this in mind, your code can look like that, for example:

procedure TForm1.Memo1KeyDown(Sender: TObject; 
  var Key: Word; Shift: TShiftState);
begin          
  if ((ssMeta in Shift) and (Key = 65)) then
    Memo1.SelectAll;  // select all
end;

If you want to compile and use the same code on Windows as well as Mac OS X (or Linux) without any change, you can use compiler switches for that purpose:

procedure TForm1.Memo1KeyDown(Sender: TObject; 
  var Key: Word; Shift: TShiftState);
begin       
  {$IFDEF DARWIN} 
    if ((ssMeta in Shift) and (Key = 65)) then
  {$ELSE}
    if ((ssCtrl in Shift) and (Key = 65)) then 
  {$ENDIF}
    Memo1.SelectAll;  // select all
end;

On Mac OS X, the code written after "DARWIN" will be compiled and with this the CMD key check, in all other cases, it will be checked for CTRL.

Alternatively, of course, you can also store the current key, then you will need only one compiler switch.

var
  AModKey: TShiftState;

procedure TForm1.FormCreate(Sender: TObject);
begin       
  {$IFDEF DARWIN} 
    AModKey := ssMeta;
  {$ELSE}
    AModKey := ssCtrl;
  {$ENDIF}
end;

procedure TForm1.Memo1KeyDown(Sender: TObject; 
  var Key: Word; Shift: TShiftState);
begin        
  if ((AModKey in Shift) and (Key = 65)) then
  Memo1.SelectAll;  // select all
end;

In this example, we have defined one global variable AModKey, which is set when creating the Form depending on the operating system. Later in our procedures, it is sufficient to only check for AModKey so that we do not have to implement any case distinction every time again.
2017-03-27 at 21:17

ReplyPositive Negative
Reply

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.

Participate

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