Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which way is the "correct" one to define a shortcut in Delphi?

There are many examples on how to define a ShortCut in a Delphi program, but they boil down to just two different ways:

  1. Add any of the scCtrl, scShift and scAlt constants to Ord() of the key
  2. Use the Menus.ShortCut function

e.g.

Action.ShortCut := scCtrl + scShift + Ord('K');
// vs
Action.ShortCut := Menus.ShortCut(Word('K'), [ssCtrl, ssShift]);

Is one of these two ways preferable? If yes, which one and why?

like image 431
dummzeuch Avatar asked Mar 26 '16 17:03

dummzeuch


1 Answers

The code is almost identical, but ShortCut has some additional checks:

function ShortCut(Key: Word; Shift: TShiftState): TShortCut;
begin
  Result := 0;
  if HiByte(Key) <> 0 then Exit; // if Key is national character then it can't be used as shortcut
  Result := Key;
  if ssShift in Shift then Inc(Result, scShift); // this is identical to "+" scShift
  if ssCtrl in Shift then Inc(Result, scCtrl);
  if ssAlt in Shift then Inc(Result, scAlt);
end;

Because RegisterHotKey function uses Virtual key codes (which has values from $00 to $FE) this additional check is significant.

Note that instead of Ord documentation, real Ord function returns smallint (signed Word), so using national characters can change modificators, that contained in Hi-byte of ShortCut value.

So, more preferably is use ShortCut function.

like image 78
kami Avatar answered Nov 16 '22 04:11

kami