关于HOOK的问题,折狂了好久(100)

  • 主题发起人 主题发起人 sher12
  • 开始时间 开始时间
S

sher12

Unregistered / Unconfirmed
GUEST, unregistred user!
当焦点在主程序窗口时,键盘钩子就能把截获的字符传到主程序但如果焦点不在主程序窗口时,消息传递就出问题了,而鼠标钩子却不会出现这个问题,焦点在哪里,主程序窗口都能接收到消息为什么??我的目的是焦点不在主程序窗口时,主程序窗口仍能收到按键消息主程序unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls;const WM_MyMessage = WM_USER + 1;type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure MyMessage(var msg: TMessage); message WM_MyMessage; {定义一个消息方法接受消息} end; function SetHook: Boolean; stdcall; function DelHook: Boolean; stdcall; function SetHWnd(hwnd: HWND): Boolean; stdcall;var Form1: TForm1;implementation{$R *.dfm}function SetHook; external 'MyHook.dll';function DelHook; external 'MyHook.dll';function SetHWnd; external 'MyHook.dll';procedure TForm1.FormCreate(Sender: TObject);begin FormStyle := fsStayOnTop; {为了测试, 让窗口一直在前面} SetHook; SetHWnd(Handle);end;procedure TForm1.FormDestroy(Sender: TObject);begin DelHook;end;{把接受到的内容显示在窗体}procedure TForm1.MyMessage(var msg: TMessage);begin Text := PChar(msg.LParam);end;end.下面是DLLlibrary MyHook;uses SysUtils, Windows, Messages, Classes, dialogs;{$R *.res}const WM_MyMessage = WM_USER + 1; {自定义消息}var hook: HHOOK; info: string; h: HWND; {用作外部窗口的句柄}{获取外部窗口的句柄}function SetHWnd(hwnd: HWND): Boolean; stdcall;begin h := hwnd; Result := True;end;function MouseHook(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;begin case wParam of WM_MOUSEMOVE : info := '鼠标位置'; WM_LBUTTONDOWN : info := '按下'; WM_LBUTTONUp : info := '放开'; end; info := Format('%s: %d,%d', [info, PMouseHookStruct(lParam)^.pt.X, PMouseHookStruct(lParam)^.pt.Y]); {通过消息把数据传递给指定窗口} PostMessage(h, WM_MyMessage, 0, Integer(PChar(info))); Result := CallNextHookEx(hook, nCode, wParam, lParam);end;function KeyboardHookHandler(iCode: Integer;wParam: WPARAM;lParam: LPARAM): LRESULT; stdcall; export;const_KeyPressMask = $80000000;begin Result := 0; //注释后就可以屏蔽键盘 If iCode < 0 Then begin Result := CallNextHookEx(hook,iCode,wParam,lParam); Exit; end; if ((lParam and _KeyPressMask) = 0) then begin info:=chr(wparam); PostMessage(h, WM_MyMessage, 0, Integer(PChar(info))); end;end;function SetHook: Boolean; stdcall;const WH_MOUSE_LL =14;begin //hook := SetWindowsHookEx(WH_MOUSE_LL, @MouseHook, HInstance, 0); Hook :=SetWindowsHookEx(WH_KEYBOARD,@KeyboardHookHandler,HInstance,0); Result := hook <> 0;end;function DelHook: Boolean; stdcall;begin Result := UnhookWindowsHookEx(hook);end;exports SetHook, DelHook, MouseHook, SetHWnd;beginend.
 
SetWindowsHookEx,看看参数吧实在不行替换目标进程的消息过程,一切都搞定!~
 
TO DstormSetWindowsHookEx的使用倒没有问题想不通鼠标钩子都行,键盘钩子为什么就不行,明明得到了数据,就是不能传到主窗口“替换目标进程的消息过程”,这个用什么方法,谢谢!!!
 
接受答案了.
 
您好,我现在也在学习windows hook ,不知道能否向您学习下呢?能给我发个例子吗?我的qq306320275.非常感谢。
 

Similar threads

I
回复
0
查看
552
import
I
I
回复
0
查看
742
import
I
I
回复
0
查看
607
import
I
后退
顶部