Mirror

Track the mouse position over a TPanel on a form (Views: 705)


Problem/Question/Abstract:

I want to track the position of the mouse over a TPanel within the client area of my main form. Using WM_MOUSEMOVE, I can track the mouse position over the main form easily enough, but once the mouse moves over my panel, the tracking stops. What do I need to do to track the position of the mouse over the panel?

Answer:

This is happening because TPanel is a different window with a handle of its own. You need to intercept the WM_MOUSEMOVE message in the TPanels WindowProc procedure. Assuming the form is TForm1 and the panel is Panel1:

First declare the following in the forms class:

private
{ Private declarations }
OldPanelWndProc: TWndMethod;

procedure NewPanelWndProc(var Message: TMessage);

Finally, implement the relevant code. Note how you should always call the old WindowProc procedure after you've handled the message. Also, WindowProc should be restored to it's original procedure when the form (containing the panel) is hidden. It would be a bad idea to restore the WindowProc procedure in the forms OnDestroy event because if it (the form) is hidden and shown again, it's going to cause problems with WindowProc being reassigned when it shouldn't be.

procedure TForm1.FormShow(Sender: TObject);
begin
  OldPanelWndProc := Panel1.WindowProc;
  Panel1.WindowProc := NewPanelWndProc;
end;

procedure TForm1.FormHide(Sender: TObject);
begin
  Panel1.WindowProc := OldPanelWndProc;
end;

procedure TForm1.NewPanelWndProc(var Message: TMessage);
begin
  case Message.Msg of
    WM_MOUSEMOVE:
      Caption := 'x = ' + inttostr(Message.LParamLo) + ' y = ' +
                         inttostr(Message.LParamHi);
  end;
  OldPanelWndProc(Message);
end;

<< Back to main page