Hook the mouse

Posted in Manipulators

This example shows a creation of a hook for the WM_RBUTTONDOWN and WM_RBUTTONUP messages of the mouse. By the first message we change color of the Panel1 and by second message we change color of the Panel2.

...
type
  TMessageList = class(TList);

var
  Form1: TForm1;
  MessageList: TMessageList = nil;
  MessageBuffer: TEventMsg;
  HookHandle: hHook = 0;
  MessageCount: Word = 0;
  Go: Boolean = False;
  Pan: array[0..5] of TPanel;

implementation

{$R *.DFM}

procedure Stop;
begin
  if Go then UnHookWindowsHookEx(HookHandle);
  MessageList.Free;
  Go:=False;
end;

function FBack(Code: Integer; wParam, lParam: LongInt): LongInt; stdcall;
begin
  Inc(MessageCount);
  Randomize;
  if MessageCount>=MessageList.Count then Stop
  else MessageBuffer:=TEventMsg(MessageList.Items[MessageCount]^);
  Result:=CallNextHookEx(HookHandle, Code, wParam, lParam);
  Pan[MessageCount].Color:=RGB(Random(255), Random(255), Random(255))
end;

procedure SetHook;
begin
  MessageBuffer:=TEventMsg(MessageList.Items[0]^);
  MessageCount:=0;
  HookHandle:=SetWindowsHookEx(WH_MOUSE, FBack, hInstance, 0);
  Go:=True;
end;

procedure MakeMessage(Mes: Cardinal);
var
  MyEvent: PEventMsg;
begin
  New(MyEvent);
  with MyEvent^ do
  begin
    message:=Mes;
    ParamL:=50;
    ParamH:=50;
    Time:=GetTickCount;
    hWnd:=Form1.Handle;
  end;
  MessageList.Add(MyEvent);
end;

function SendMouse: Integer;
begin
  try
    MessageList:=TMessageList.Create;
    MakeMessage(WM_RBUTTONDOWN);
    MakeMessage(WM_RBUTTONUP);
    SetHook;      // set hook
  except
  end;
  Result:=0;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Pan[1]:=panel1;
  Pan[2]:=Panel2;
  SendMouse;
end;