function PlayProc(iCode:Integer;wParam:wParam;lParam:lParam):LRESULT;stdcall;
begin
canPlay:=1;
Result:=0;
if iCode < 0 then //必须将消息传递到钩子链的下一个处理程序
Result := CallNextHookEx(hPlay,iCode,wParam,lParam)
else if iCode = HC_SYSMODALON then canPlay:=0
else if iCode = HC_SYSMODALOFF then canPlay:=1
else if ((canPlay =1 )and(iCode=HC_GETNEXT)) then begin
if bDelay then begin
bDelay:=False;
Result:=50;//控制回放的速度,数字越大,越慢
end;
pEventMSG(lParam)^:=EventArr[PlayLog];
end
else if ((canPlay = 1)and(iCode = HC_SKIP))then begin
bDelay := True;
PlayLog:=PlayLog+1;
end;
if PlayLog>=EventLog then begin
UNHookWindowsHookEx(hPlay);
end;
end;
function HookProc(iCode:Integer;wParam:wParam;lParam:lParam):LRESULT;stdcall;
begin
recOK:=1; //可以记录
Result:=0;
if iCode < 0 then //必须将消息传递到钩子链的下一个处理程序
Result := CallNextHookEx(hHook,iCode,wParam,lParam)
else if iCode = HC_SYSMODALON then recOK:=0
else if iCode = HC_SYSMODALOFF then recOK:=1
else if ((recOK>0) and (iCode = HC_ACTION)) then begin
EventArr[EventLog]:=pEventMSG(lParam)^;
EventLog:=EventLog+1;
if EventLog>=1000 then begin
UnHookWindowsHookEx(hHook);
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Button1.Caption:='纪录';
Button2.Caption:='停止';
Button3.Caption:='回放';
Button2.Enabled:=False;
Button3.Enabled:=False;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
EventLog:=0;
//建立键盘、鼠标操作消息纪录链
hHook:=SetwindowsHookEx(WH_JOURNALRECORD,HookProc,HInstance,0);
Button2.Enabled:=True;
Button1.Enabled:=False;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
UnHookWindowsHookEx(hHook);
hHook:=0;
Button1.Enabled:=True;
Button2.Enabled:=False;
Button3.Enabled:=True;
end;
~~三、小结
Hook是应用程序在Microsoft Windows 消息处理过程中设置的用来监控消息流并且处理系统中尚未到达目的窗口的某一类型消息过程的机制。这可以帮助应用程序实现实现某些特殊目的,如控制键盘或鼠标的输入消息,监视窗口的打开关闭以及实现记录宏等等,应用灵活,功能强大。如果Hook过程在应用程序中实现,若应用程序不是当前窗口时,该Hook就不起作用;如果Hook在DLL中实现,程序在运行中动态调用它,它能实时对系统进行监控。
参考文献
1.Jeffrey Richter. Advanced Windows third edition. Microsoft Press, 1997
2.Feffrey Richter. Windows95 WindowsNT3.5 高级编程技术. 清华大学出版社,1996年
责任编辑:敖剑