How can I handle a keyboard shortcut when my program isn't active?

后端 未结 3 1295
走了就别回头了
走了就别回头了 2021-01-06 11:44

Is it ok if i use it like this..for multiple events?

unit Unit4;

interface

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


        
3条回答
  •  猫巷女王i
    2021-01-06 12:08

    Use the RegisterHotKey function. If you want the application to be invisible, you might want all the details in my answer to a similar question.

    Try this:

    unit Unit4;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, Clipbrd;
    
    type
      TForm4 = class(TForm)
        procedure FormCreate(Sender: TObject);
        procedure WMHotkey(var Message: TWMHotKey); message WM_HOTKEY;
        procedure FormDestroy(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;
    
    var
      Form4: TForm4;
    
    implementation
    
    const
      MY_ID = 123;
    
    {$R *.dfm}
    
    procedure TForm4.FormCreate(Sender: TObject);
    begin
      RegisterHotKey(Handle, MY_ID, MOD_CONTROL, ord('1'));
    end;
    
    procedure TForm4.FormDestroy(Sender: TObject);
    begin
      UnregisterHotKey(Handle, MY_ID);
    end;
    
    procedure TForm4.WMHotkey(var Message: TWMHotKey);
    begin
      if Message.HotKey = MY_ID then
      begin
    
        if not AttachThreadInput(GetCurrentThreadId, GetWindowThreadProcessId(GetForegroundWindow), true) then
          RaiseLastOSError;
    
        try
          Clipboard.AsText := 'This is my own text!';
          SendMessage(GetFocus, WM_PASTE, 0, 0);
        finally
          AttachThreadInput(GetCurrentThreadId, GetWindowThreadProcessId(GetForegroundWindow), false);
        end;
    
      end;
    end;
    
    end.
    

    Of course, you will need to use this approach and modify it so it suits your particular case. (That is, you probably want something more than an application that prints "This is my own text!" on Ctrl+1, but nothing else.)

提交回复
热议问题