Author: Tomas Rutkauskas
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:
1 private2 { Private declarations }3 OldPanelWndProc: TWndMethod;
4 5 procedure NewPanelWndProc(varmessage: 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.
6 procedure TForm1.FormShow(Sender: TObject);
7 begin8 OldPanelWndProc := Panel1.WindowProc;
9 Panel1.WindowProc := NewPanelWndProc;
10 end;
11 12 procedure TForm1.FormHide(Sender: TObject);
13 begin14 Panel1.WindowProc := OldPanelWndProc;
15 end;
16 17 procedure TForm1.NewPanelWndProc(varmessage: TMessage);
18 begin19 casemessage.Msg of20 WM_MOUSEMOVE:
21 Caption := 'x = ' + inttostr(message.LParamLo) + ' y = ' +
22 inttostr(message.LParamHi);
23 end;
24 OldPanelWndProc(message);
25 end;