每个程序都有自己的生存空间,在Windows系统中你可以在任何时候让你的程序执行一些操作,还可以触发消息,触发的消息分为三种,一是操作你程序的界面,onClick,onMouseMove等等,另外一个可以使用Windows的消息机制来捕获一些系统消息,但是如果你想在任何时候监控任何程序的情况那可能你就会选择HOOK来实现了,虽然还有其他方法,但不得不承认,HOOK是一个比较简单解决问题的途径。
Windows提供了Hook机制,定义为
A callback function provided by an application that receives certain data before the normal recipient of the data. The hook function can thus examine or modify the data before passing it on.
可以使用诸多Hook的方式,一下列举一些常用的参数,这些在WINDWOS API帮助中都有:
CALLWNDPROC ,CALLWNDPROCRET :
The WH_CALLWNDPROC and WH_CALLWNDPROCRET hooks enable you to monitor messages sent to window procedures by the SendMessage function. Windows calls a WH_CALLWNDPROC hook procedure before passing the message to the receiving window procedure, and calls the WH_CALLWNDPROCRET hook procedure after the window procedure has processed the message.
CBT:
Windows calls a WH_CBT hook procedure before activating, creating, destroying, minimizing, maximizing, moving, or sizing a window; before completing a system command; before removing a mouse or keyboard event from the system message queue; before setting the input focus; or before synchronizing with the system message queue. The value the hook procedure returns determines whether Windows allows or prevents one of these operations. The WH_CBT hook is intended primarily for computer-based training (CBT) applications.
KEYBOARD:
he WH_KEYBOARD hook enables an application to monitor message traffic for WM_KEYDOWN and WM_KEYUP messages about to be returned by the GetMessage or PeekMessage function. You can use the WH_KEYBOARD hook to monitor keyboard input posted to a message queue.
下面就来举个例子(使用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(hMapOb