TApplicationEvents.OnShortCut:只检测带有修饰键的键?

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

我在 Delphi 11 Alexandria 中使用 TApplicationEvents.OnShortCut 事件,在 Windows 10 中使用 Delphi VCL 应用程序,例如:

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

不幸的是,即使没有按下修饰键也会触发此事件,例如单独使用“V”键或“B”键。如何在没有按下修改键时退出此事件处理程序,例如:

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

您可以使用单元 Winapi.Windows 中的 GetKeyState 函数,以及 VK_CONTROL 或 VK_SHIFT 等虚拟键码。例如:

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;

考虑到@RemyLebeau 和@Andreas Rejbrand 的友好评论:

这对我有用:

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