RegisterHotKey

Recently I needed a system-wide hotkey, Ctrl + F1, that would bring my Delphi application to the foreground.

This can be done using the Windows RegisterHotKey API and handling the WM_HOTKEY message.


System-Wide Hotkey

First, add the required Windows units:

uses
  Winapi.Windows,
  Winapi.Messages;

Add a hotkey identifier and a message handler to the form:

private
  const HotKeyId = 1;

  procedure WMHotKey(var Msg: TWMHotKey); message WM_HOTKEY;

Register the hotkey in the form's OnCreate event:

procedure TForm1.FormCreate(Sender: TObject);
begin
  if not RegisterHotKey(Handle, HotKeyId, MOD_CONTROL, VK_F1) then
    RaiseLastOSError;
end;

The call will fail if the requested key combination cannot be registered, for example if another application has already registered it.

Unregister the hotkey when the form is destroyed:

procedure TForm1.FormDestroy(Sender: TObject);
begin
  UnregisterHotKey(Handle, HotKeyId);
end;

Finally, handle the WM_HOTKEY message:

procedure TForm1.WMHotKey(var Msg: TWMHotKey);
begin
  if Msg.HotKey = HotKeyId then
    WinActivate(Handle);
end;

Bring the Application to the Front

The activation function restores the window if it is minimized, then asks Windows to bring it to the foreground:

class function TForm1.WinActivate(const AHandle: HWND): Boolean;
begin
  if IsIconic(AHandle) then
    ShowWindow(AHandle, SW_RESTORE);

  Result := SetForegroundWindow(AHandle);
end;

We use the form's window handle directly, avoiding the need to locate the window by its caption.