dummzeuch
dummzeuch

Reputation: 11217

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?

Upvotes: 11

Views: 1233

Answers (2)

kami
kami

Reputation: 1458

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.

Upvotes: 15

ciuly
ciuly

Reputation: 552

I'd say that whenever there is a function that does the job, it is better to use the function.

Because given the chance in the future that something changes, having a function gives you a "hard link" to the call, so if the function becomes deprecated, you are notified, and if the function logic changes, you get the update silently.

Otherwise, you will not benefit from this.

Now in this particular case, what are the chances for the definition of a shortcut to change in the next 10-20 years? Probably none. But I'd still advocate the function call (if not for anything, but you don't have to remember the logic (was it addition or was it logical ORing? one might ask himself later on)

Upvotes: 5

Related Questions