Adding a hotkey to a Delphi application

Let's say I have a form that has a menu bar on it. I have an item in the menu bar, TMenuItem, for which I can assign a keyboard shortcut, for example, "Ctrl-I". But when I assign the β€œShortCut” property to TMenuItem, it seems I just changed the appearance of the menu item to show the shortcut code, rather than automatically listening to the shortcut key press and running my ActionManager code.

Today my google-fu is failing, I only find articles on how to assign global hotkeys for Windows, and not how to assign hotkeys to applications that only work in active form.

Can someone outline for me the steps necessary to add a hotkey, in addition to adding a shortcut property to the menu. I think somewhere I probably need to set up a form to listen for keyboard input and capture a keystroke and respond to it? But I'm not quite sure where and what Delphi can do.

+5
source share
2 answers

You seem to be using an Action (ActionManager), so instead assign your shortcut to the appropriate Action. (Assigning an Action to MenuItem will also assign a shortcut to a menu item.)

+6
source

VCL, WM_HOTKEY. Windows, , :

type
TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
    // Declare a event handler
     procedure WMHotKey(var Msg: TWMHotKey); message WM_HOTKEY;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
   // Registering a hotkey Ctrl+Alt+F5
   RegisterHotKey(Handle, 0, MOD_CONTROL or MOD_ALT, VK_F5);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  // Unregisters a hotkey
   UnRegisterHotKey(Handle, 0);
end;

procedure TForm1.WMHotKey(var Msg: TWMHotKey);
begin
   // This procedure is called when a window message WM_HOTKEY
   inherited;  // We give the form to process the message,
               // if she already has its handler
   Beep;       // We perform additional actions
end;
-1

All Articles