API - exemplo de hook de teclado simples

Top  Previous  Next

// Exemplo SIMPLES de HOOK de TECLADO

 

var

  Form1: TForm1;

  qtHookKey : HHOOK;

  qtHookWnd : HHOOK;

 

implementation

 

uses Unit2;

 

{$R *.DFM}

 

function qtWinProcKey(code: Integer; wparam: WParam; lparam: LParam): LResult; stdcall;

begin

  Result := -1;

  if (wparam = VK_ESCAPE) then

  begin

    if Screen.ActiveForm = Form1 then Screen.ActiveForm.Close;

    Result := 0;

    Exit;

  end;

  Result := CallNextHookEx(qtHookKey, code, wparam, lparam);

end;

 

function qtWinProcWnd(code: Integer; wparam: WParam; lparam: LParam): LResult; stdcall;

begin

  CallNextHookEx(qtHookWnd, code, wparam, lparam);

  Result := 0;

end;

 

procedure TForm1.FormCreate(Sender: TObject);

begin

  qtHookKey := SetWindowsHookEx(WH_KEYBOARD, qtWinProcKey, 0, GetCurrentThreadId);

  qtHookWnd := SetWindowsHookEx(WH_CALLWNDPROC, qtWinProcWnd, 0, GetCurrentThreadId);

end;

 

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);

begin

  UnhookWindowsHookEx(qtHookKey);

  UnhookWindowsHookEx(qtHookWnd);

end;

 

procedure TForm1.Button1Click(Sender: TObject);

begin

  form2.Show;

end;