Windows環境でシステム全体にマウス操作を監視するためには、DLLを通じたグローバルフックの実装が必須です。以下の2段階の手順で実現可能です:
- フック機能を提供するDLLモジュールの作成
- 作成したDLLを呼び出すテストアプリケーションの実装
フックDLLの実装例
library GlobalMouseHook;
uses
SysUtils,
Windows,
Messages;
var
hHook: HHOOK;
// マウス左クリックイベントを捕捉するコールバック関数
function HookProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
begin
if wParam = WM_LBUTTONDOWN then
MessageBeep(0); // クリック音を鳴らす
Result := CallNextHookEx(hHook, nCode, wParam, lParam);
end;
// フックの設定
function InitializeHook: Boolean; stdcall;
begin
hHook := SetWindowsHookEx(WH_MOUSE, @HookProc, HInstance, 0);
Result := hHook <> 0;
end;
// フックの解除
function ReleaseHook: Boolean; stdcall;
begin
Result := UnhookWindowsHookEx(hHook);
end;
exports
InitializeHook name 'InitHook',
ReleaseHook name 'ReleaseHook',
HookProc name 'HookCallback';
begin
end.
テストアプリケーションの実装
静的リンク方式
unit TestApp;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
StartButton: TButton;
StopButton: TButton;
procedure StartButtonClick(Sender: TObject);
procedure StopButtonClick(Sender: TObject);
private
function InitHook: Boolean; stdcall; external 'GlobalMouseHook.dll' name 'InitHook';
function ReleaseHook: Boolean; stdcall; external 'GlobalMouseHook.dll' name 'ReleaseHook';
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.StartButtonClick(Sender: TObject);
begin
InitHook;
end;
procedure TForm1.StopButtonClick(Sender: TObject);
begin
ReleaseHook;
end;
end.
動的リンク方式
unit DynamicTestApp;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
StartButton: TButton;
StopButton: TButton;
procedure StartButtonClick(Sender: TObject);
procedure StopButtonClick(Sender: TObject);
private
dllHandle: HMODULE;
HookInit: function: Boolean; stdcall;
HookRelease: function: Boolean; stdcall;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.StartButtonClick(Sender: TObject);
begin
dllHandle := LoadLibrary('GlobalMouseHook.dll');
if dllHandle <> 0 then
begin
@HookInit := GetProcAddress(dllHandle, 'InitHook');
@HookRelease := GetProcAddress(dllHandle, 'ReleaseHook');
HookInit;
end;
end;
procedure TForm1.StopButtonClick(Sender: TObject);
begin
HookRelease;
FreeLibrary(dllHandle);
end;
end.
グローバルフックのDLL依存性について
EXEアプリケーションはそれぞれ独立したプロセス空間を持つため、直接他のプロセスにフックを設定できません。一方DLLはシステム全体からアクセス可能な共有リソースとして設計されており、これがグローバルフックを実現する技術的な根拠となっています。