Search code examples
delphihidehotkeystray

Using hotkey even if window hide in tray. Is it possible in Delphi?


I need to hide a form to the system tray, but in the same time I want to use hotkey, such a "ctrl+3" to get text from tEdit on my hiden form being inserted to Firefox SendText(edit1.Text); // in such method'. I know how to insert text, but i don't know anything about hotkeys/ Any suggestions? Thank you. Code of text inserting below

procedure SendText(const Value: WideString);
var
  I: Integer;
  S: WideString;
  TI: TInput;
  KI: TKeybdInput;
const
  KEYEVENTF_UNICODE = $0004;
begin
  S := WideUpperCase(Value); 
  TI.Itype := INPUT_KEYBOARD;
  for I := 1 to Length(S) do
  begin
    KI.wVk := 0;
    KI.dwFlags := KEYEVENTF_UNICODE;
    KI.wScan := Ord(S[I]);
    TI.ki := KI;
    SendInput(1, TI, SizeOf(TI));
  end;
end;

Solution

  • To Register a system wide hotkey you must use the RegisterHotKey and UnRegisterHotKey functions.

    Check this sample

    type
      TForm125 = class(TForm)
        procedure FormCreate(Sender: TObject);
        procedure FormDestroy(Sender: TObject);
      private
        HotKey1 : Integer;
        procedure WMHotKey(var Msg: TWMHotKey); message WM_HOTKEY;
      public
    
      end;
    
    var
      Form125: TForm125;
    
    implementation
    
    {$R *.dfm}
    
    
    procedure TForm125.FormCreate(Sender: TObject);
    begin
      HotKey1 := GlobalAddAtom('MyAppHotkey1');//create a unique value for identify the hotkey
      if not RegisterHotKey(Handle, HotKey1, MOD_CONTROL, VK_F1) then //register the hotkey CTRL + F1
       ShowMessage('Sorry can not register the hotkey');
    end;
    
    procedure TForm125.FormDestroy(Sender: TObject);
    begin
      UnRegisterHotKey(Handle, HotKey1);//unregister the hotkey
      GlobalDeleteAtom(HotKey1);//remove the atom
    end;
    
    procedure TForm125.WMHotKey(var Msg: TWMHotKey);
    begin
      if Msg.HotKey = HotKey1 then
        ShowMessage('Hello'); // do your stuff
    end;
    

    Just be carefull about the key combination which you choose, because can be used internally for another app. for example the combination Ctrl Number is used by Firefox to switch the tabs.