unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;type
  TForm1 = class(TForm)
    Edit1: TEdit;
    ButtonHook: TButton;
    ButtonUnhook: TButton;
    Label1: TLabel;
    Memo1: TMemo;
    procedure ButtonHookClick(Sender: TObject);
    procedure ButtonUnhookClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;var
  Form1: TForm1;
  hookHandle: HHook;function KeyboardCallback(code, wParam, lParam: Integer): HRESULT; stdcall;implementation{$R *.dfm}procedure TForm1.ButtonHookClick(Sender: TObject);
var
  threadId: Integer;
begin
  threadId := StrToInt(edit1.Text);
  hookHandle := SetWindowsHookEx(WH_KEYBOARD, @KeyboardCallback, HInstance, threadId);
  if (hookHandle = 0) then
    ShowMessage('hook error');
end;procedure TForm1.ButtonUnhookClick(Sender: TObject);
begin
  if (hookHandle <> 0) then begin
    UnhookWindowsHookEx(hookHandle);
    hookHandle := 0;
  end;
end;function KeyboardCallback(code, wParam, lParam: Integer): HRESULT; stdcall;
begin
  if wParam = WM_KEYDOWN then begin
    if lParam = VK_F1 then begin
      Form1.Memo1.Text := 'okokok';
    end;
  end;
  Result := CallNextHookEx(hookHandle, code, wParam, lParam);
end;end.
=====================
以上是我得代码,晕死,搞了1天没搞明白,进行了HOOK之后在被HOOK窗体按F1就提示程序错误。哪位高手给个代码呀?

解决方案 »

  1.   

    我不想搞出个DLL得方法,想使用一个文件。
      

  2.   

    不用DLL要钩住其他程序的按键,只能用日志钩子。
    具体用法请看这里:
    blog.csdn.net/linzhengqun
    找钩子及其应用。
      

  3.   

    hookHandle := SetWindowsHookEx(WH_KEYBOARD, @KeyboardCallback, HInstance, threadId);
    这一行代码,用了HInstance,后面一个参数就要设置为0 ,如果后面一个参数设置为险程ID,那么前一个参数就要设置成0下面是正确的
    hookHandle := SetWindowsHookEx(WH_KEYBOARD, @KeyboardCallback, 0, GetCurrentThreadID);
    hookHandle := SetWindowsHookEx(WH_KEYBOARD, @KeyboardCallback, HInstance, 0);
      

  4.   

    上面的可能还有点不清楚,帮助里面是这么说的
    hModIdentifies the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process. dwThreadIdSpecifies the identifier of the thread with which the hook procedure is to be associated. If this parameter is zero, the hook procedure is associated with all existing threads.