Global system hotkey

Using the RegisterHotKey function and few other lines of code, you can register a global system hotkey, which is active even if your application is minimized.

First, you must create a WMHotKey procedure to catch a system WM_HOTKEY message. And then, you must define (in OnCreate event of main form) which hotkey you want to register and which action should be taken after you press it. Finally, in OnDestroy event of main form, you should unregister your hotkeys.

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;

type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
hotkey1, hotkey2: Integer;
procedure WMHotKey(var Msg : TWMHotKey); message WM_HOTKEY;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.WMHotKey (var Msg : TWMHotKey);
begin
if msg.HotKey = hotkey1 then ShowMessage('Ctrl + A pressed');
if msg.HotKey = hotkey2 then ShowMessage('Ctrl + B pressed');
end;

procedure TForm1.FormCreate(Sender: TObject);
const MOD_CONTROL = 2;
VK_A = 65;
VK_B = 66;
begin
hotkey1 := GlobalAddAtom('Hotkey1');
RegisterHotKey(handle, hotkey1, MOD_CONTROL,VK_A);
hotkey2 := GlobalAddAtom('Hotkey2');
RegisterHotKey(handle, hotkey2, MOD_CONTROL,VK_B);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
UnRegisterHotKey(handle, hotkey1);
UnRegisterHotKey(handle, hotkey2);
end;

end.

Leave a Reply