用hook函数
你要监视任何一个程序的鼠标动作.必须使用dll动态连接库来拦截鼠标消息.
SetWindowsHookEx(int idHook,HOOKPROC lpfn, HINSTANCE hMod,
DWORD dwThreadId);
其中 idhook ->钩子的类型
lpfn ->回调函数的地址
hmod ->应用程序实例的句柄
dwthreadid ->钩子函数所对应的线程
例子: hnexthookproc:=setwindowshookex(WH_MOUSE,@YourProcedure,hinstance,0);
idhook 钩子类型.你可以根据需要选择.
lpfn 替换钩子的程序
hnexthookpro为hook变量.
dwthreadid应为0,这样对所有程序都可用.
hmod应为hinstance,这样再dll中,对所有程序的线程都可用.
CallNextHookEx(HHOOK hhk,int nCode,WPARAM wParam,LPARAM lParam);
其中 hhk ->替换钩子程序的句柄
ncode ->替换钩子程序(你的程序yourprocedure)中的icode
wparam ->消息的附加信息
lparam ->消息的附加信息
例子: result := callnexthookex(hnexthookproc, icode, wp, longint(@Msg));
callnexthookex必须出现在yourprocedure中, 档调用失败或成功时,都必须用此函数
来回放钩住的信息
UnhookWindowsHookEx(HHOOK hhk);
其中 hhk ->替换钩子程序的句柄
例子:unhookwindowshookex(hnexthookproc);
当不是用钩子时,必须释放它
送你一个钱达智先生的键盘钩子的例子:
library HKTest;
uses
HKProc in 'HKProc.pas';
exports
EnableHotKeyHook,
DisableHotKeyHook;
begin
hNextHookProc := 0;
procSaveExit := ExitProc;
ExitProc := @HotKeyHookExit;
end.
unit HKProc;
interface
uses
Windows, Messages;
var
hNextHookProc: HHook;
procSaveExit: Pointer;
function KeyboardHookHandler(iCode: Integer;
wParam: WPARAM;
lParam: LPARAM): LRESULT; stdcall; export;
function EnableHotKeyHook: BOOL; export;
function DisableHotKeyHook: BOOL; export;
procedure HotKeyHookExit; far;
implementation
function KeyboardHookHandler(iCode: Integer;
wParam: WPARAM;
lParam: LPARAM): LRESULT; stdcall; export;
const
_KeyPressMask = $80000000;
begin
Result := 0;
If iCode < 0 Then
begin
Result := CallNextHookEx(hNextHookProc, iCode, wParam, lParam);
Exit;
end;
if ((lParam and _KeyPressMask) = 0) and
(GetKeyState(vk_Control) < 0) and (wParam = Ord('B')) then
begin
Result := 1;
WinExec('Notepad.exe', sw_Normal);
end;
end;
function EnableHotKeyHook: BOOL; export;
begin
Result := False;
if hNextHookProc <> 0 then Exit;
hNextHookProc := SetWindowsHookEx(WH_KEYBOARD,
KeyboardHookHandler,
HInstance,
0);
Result := hNextHookProc <> 0;
end;
function DisableHotKeyHook: BOOL; export;
begin
if hNextHookProc <> 0 then
begin
UnhookWindowshookEx(hNextHookProc);
hNextHookProc := 0;
MessageBeep(0);
MessageBeep(0);
end;
Result := hNextHookProc = 0;
end;
procedure HotKeyHookExit;
begin
if hNextHookProc <> 0 then DisableHotKeyHook;
ExitProc := procSaveExit;
end;
end.
implementation
{$R *.DFM}
function EnableHotKeyHook: BOOL; external 'HKTEST.DLL';
function DisableHotKeyHook: BOOL; external 'HKTEST.DLL';
procedure TForm1.Button1Click(Sender: TObject);
begin
if EnableHotKeyHook then
ShowMessage('HotKey Testing...');
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if DisableHotKeyHook then
ShowMessage('HotKey Testing..., DONE!!');
end;
end.