user1580348
user1580348

Reputation: 6061

TApplicationEvents.OnShortCut: Detect only Keys with modifier-key?

I use the TApplicationEvents.OnShortCut event in Delphi 11 Alexandria with a Delphi VCL Application in Windows 10, for example:

procedure TformMain.ApplicationEvents1ShortCut(var Msg: TWMKey; var Handled: Boolean);
begin
  CodeSite.Send('TformMain.ApplicationEvents1ShortCut: Msg.CharCode', Msg.CharCode);
end;

Unfortunately, this event is even triggered when no modifier key is pressed, e.g. the "V" key or the "B" key alone. How can I exit this event handler when no modifier key is pressed, for example:

procedure TformMain.ApplicationEvents1ShortCut(var Msg: TWMKey; var Handled: Boolean);
begin
  if NoModifierKeyPressed then EXIT;
  ...
end;

Upvotes: 0

Views: 887

Answers (3)

Dżyszla
Dżyszla

Reputation: 79

    procedure TformMain.ApplicationEvents1ShortCut(var Msg: TWMKey; var Handled: Boolean);
    begin
        if KeyDataToShiftState(Msg.KeyData) = [] then ... ;
    end;

Simplest as possible. Using GetKeyState or GetKeyboardState is wrong, because get current state not from fired shortcut.

Upvotes: 2

user1580348
user1580348

Reputation: 6061

Taking into account the kind comments of @RemyLebeau and @Andreas Rejbrand:

This works for me:

function NoModifierKeyPressed: Boolean;
var
  keys: TKeyboardState;
begin
  GetKeyboardState(keys);
  Result := (keys[VK_SHIFT] and $80 = 0) and (keys[VK_CONTROL] and $80 = 0) and (keys[VK_MENU] and $80 = 0);
end;

Upvotes: 1

Matthias B
Matthias B

Reputation: 1087

You can use the GetKeyState function from unit Winapi.Windows, together with virtual key codes such as VK_CONTROL or VK_SHIFT. For example:

procedure TformMain.ApplicationEvents1ShortCut(var Msg: TWMKey; var Handled: Boolean);
begin
  if (Msg.CharCode = Ord('V')) and (GetKeyState(VK_CONTROL) < 0) then
    ShowMessage('Ctrl+V was pressed');
end;

Upvotes: 3

Related Questions