是用要到Hook
// 全局Dll鼠标钩子
library Project2;
{ 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
windows,
messages;
{$R *.res}
const
USER_WM_MOUSEDOWN = WM_USER + 1000;
var g_hHook:HHOOK;
Function MouseProc(nCode
WORD; Wparam:LongWord; LParam:LongWord):LResult; stdcall;
var hMyWindow:HWND;
begin
Result := 0;
CallNextHookEx(g_hHook,nCode,Wparam,Lparam);
if Wparam = WM_LBUTTONDOWN then
begin
hMyWindow := FindWindow(nil,'Form1');
if hMyWindow <> 0 then
PostMessage(hMyWindow,USER_WM_MOUSEDOWN,0,0);
end;
end;
Function OnHook():LResult;
begin
g_hHook := SetWindowsHookEx(WH_MOUSE,@MouseProc,hInstance,0);
Result := g_hHook;
end;
Function UnHook():Boolean;
begin
Result := FALSE;
if g_hHook <> 0 then
begin
Result := UnHookWindowsHookEx(g_hHook);
g_hHook := 0;
end;
end;
exports
OnHook,
UnHook;
begin
end.
// Demo演示程序
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
const
USER_WM_MOUSEDOWN = WM_USER + 1000;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
procedure UserWmMouseDown(var Msg:TMessage); message USER_WM_MOUSEDOWN;
{ Private declarations }
public
{ Public declarations }
end;
Function OnHook:LResult; external 'Project2.dll';
Function UnHook:Boolean; external 'Project2.dll';
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.UserWmMouseDown(var Msg: TMessage);
var Point:TPoint;
hWindow:HWND;
begin
GetCursorPos(Point);
{ 显示Screen屏幕座标 }
Label3.Caption := Format('X: %u - Y: %u',[Point.X,Point.Y]);
hWindow := WindowFromPoint(Point);
windows.ScreenToClient(hWindow,point);
// 显示窗口座标
{ 注:窗口座标是相对于鼠标所指向的子窗口的座标。
如鼠标是指向某个窗口的Toolbar控件,那窗口座标就是相对于Toolbar控件的}
Label4.Caption := Format('X: %u - Y: %u',[Point.X,Point.Y]);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetWindowPos(handle,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE OR SWP_NOSIZE);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
OnHook();
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
UnHook();
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
UnHook();
end;
end.