library hk;
uses sysutils,classes,hkproc in 'hkproc.pas';
exports enablehook,disablehook;
begin
hNextHookProc:=0;
procSaveExit:=ExitProc;
ExitProc:=@HookExit;
end.
unit hkproc;
interface
uses windows,messages,SysUtils;
var
hNextHookProc:HHook;
ff:textfile;
//procSaveExit
ointer;
function HookHandler(iCode:integer;wParam:wParam;lParam:lParam):LResult;stdcall;export;
function EnableHook:BOOL;export;
function DisableHook:BOOL;export;
//procedure HookExit;
implementation
function HookHandler(iCode:integer;wParam:wParam;lParam:lParam):LResult;stdcall;export;
//const
//_KeyPressMask=$80000000;
begin
result:=0;
if iCode<0 then
begin
result:=CallNextHookEx(hNextHookProc,iCode,wParam,lParam);
exit;
end;
writeln(ff,inttostr(iCode)+' '+inttostr(wParam)+' '+inttostr(lParam));
end;
function EnableHook:BOOL;export;
begin
result:=false;
if hNextHookProc<>0 then exit;
hNextHookProc:=SetWindowsHookEx(WH_KEYBOARD,HookHandler,Hinstance,0);
result:=hNextHookProc<>0;
assignfile(ff,'e:/aa.txt');
rewrite(ff);
end;
function DisableHook:BOOL;export;
begin
if hNextHookProc<>0 then
begin
UnhookWindowsHookex(hNextHookProc);
hNextHookProc:=0;
end;
result:=hNextHookProc=0;
closefile(ff);
end;
{procedure HookExit;
begin
if hNextHookProc<>0 then DisableHook;
ExitProc:=ProcSaveExit;
end;}
end.
把上面的程序编译成DLL后 在程序中用下面的方法调用
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
function EnableHook:BOOL; external 'hook.dll';
function DisableHook:BOOL; external 'hook.dll';
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
EnableHook();
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
disablehook();
end;
end.