我最近也在写一个关于键盘钩子的程序,以下是从我的程序改过来的,相信是
通用于钩子函数的.
//SETHOOK.PAS
VAR HK:HHOOK;
procedure SetHookFunc();
var
GetMsgProc:tfnhookproc;
hlib:thandle;
begin
if not isHooked then begin
hlib:=loadlibrary('YOURHOOKFILE.DLL');
if hlib<32 then begin
messagedlg('Not found DLL',mterror,[mbok],0);
exit;
end;
GetMsgProc:=tfnhookproc(getprocaddress(hlib,'GetMsgProc'));
hk:=setwindowshookex(WH_GETMESSAGE,GetMsgProc,hlib,0);
if hk=null then
messagedlg('Set hook error',mterror,[mbok],0)
else
isHooked:=true;
end;
end;
procedure UnHookFunc();
var
result:boolean;
begin
if isHooked then begin
result:=unhookwindowshookex(hk);
if result=false then
messagedlg('Unhook error',mterror,[mbok],0)
else
isHooked:=false;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
isHooked:=false;
SetHookFunc();
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
UnHookFunc();
end;
//YOURHOOKFILE.DPR
library YOURHOOKFILE;
{ Important note about DLL memory management: ShareMem must be the
first unit in your library's USES clause AND your project's (select
Project-View Source) USES clause if your DLL exports any procedures or
functions that pass strings as parameters or function results. This
applies to all strings passed to and from your DLL--even those that
are nested in records and classes. ShareMem is the interface unit to
the BORLNDMM.DLL shared memory manager, which must be deployed along
with your DLL. To avoid using BORLNDMM.DLL, pass string information
using PChar or ShortString parameters. }
uses
SysUtils,
Classes,
MESSAGEMAP in 'MESSAGEMAP.pas';
exports
GetMsgProc name'GetMsgProc';
begin
end.
//MESSAGEMAP.PAS
//函数定义
function GetMsgProc(ncode:integer;wp:wparam;lp:lparam):lresult;stdcall;export;
//函数实现。
function GetMsgProc (ncode:integer;wp:wparam;lp:lparam):lresult;
begin
result:=0;//The return value should be zero.
if ncode=HC_ACTION then begin
//Write your code here.
end;
end;