这是我写的 DLL Mouse Hook ,能钩到本程序的 Mouse 消息,但是不能钩到其他应用程序
中的消息,onedolph 大虾说过钩不住,能不能说明一下原因和解决方案?
library MouseHook;
uses
SysUtils,
Classes,
Windows,
Messages,
StdCtrls,
Controls,
Dialogs;
var
hHook: THandle;
ListBox: TListBox;
function MouseProc(nCode: Integer;
wParam: Word;
lParam: Integer): Integer;
begin
if (nCode < 0) then
begin
Result := CallNextHookEx(WH_MOUSE, nCode, wParam, lParam);
Exit;
end;
ListBox.Items.Add(IntToStr(GetCursor));
Result := CallNextHookEx(WH_MOUSE, nCode, wParam, lParam);
end;
procedure InstallHook(P: Pointer);
begin
ListBox := P;
hHook := SetWindowsHookEx(WH_MOUSE, @MouseProc, hInstance, 0);
if hHook = 0 then
Raise Exception.Create('Cannot set hook !');
end;
procedure UnInstallHook;
begin
ListBox := nil;
UnHookWindowsHookEx(hHook);
end;
exports InstallHook, UnInstallHook;
{$R *.RES}
begin
end.
下面是设置钩子的代码,用了一个 ListBox 来反映结果。
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Excel2000, OleServer, Word2000, ExtCtrls;
type
TFormDemo = class(TForm)
ListBox1: TListBox;
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
InstallHook: procedure (P: Pointer);
UnInstallHook: procedure;
var
FormDemo: TFormDemo;
DllHandle: THandle;
List: TListBox;
implementation
{$R *.DFM}
procedure TFormDemo.Button1Click(Sender: TObject);
begin
List := ListBox1;
InstallHook(List);
end;
procedure TFormDemo.FormCreate(Sender: TObject);
begin
DllHandle := LoadLibrary('MouseHook.Dll');
InstallHook := GetProcAddress(DllHandle, PChar('InstallHook'));
UnInstallHook := GetProcAddress(DllHandle, PChar('UnInstallHook'));
end;
procedure TFormDemo.FormDestroy(Sender: TObject);
begin
FreeLibrary(DllHandle);
end;
procedure TFormDemo.Button2Click(Sender: TObject);
begin
UnInstallHook;
end;
end.