Problem
I would like to simplify the following code in Delphi XE6 on Windows, which becomes unmaintainable as I am adding more and more types of components.
Portability note: I would like to use the same code later in Lazarus 2.0.2 on Linux with little to no change, so the Windows message handling is out of the question.
The problem is, I can't seem to find a way to assign the OnMouseEnter event handler to all components on the whole Form.
I tried all I could including various classes common in their object tree. The OnMouseEnter event seems to be nowhere in the common ground.
The event handler itself contains just one command (procedure = void function), and it will have no more, maybe this could simplify the whole problem?
As you can see below, at this moment I need to add each type of component (currently only TLabel, TButton, and TEdit) to the for-loop.
procedure TFormMain.FormCreate(Sender: TObject);
var
I: Integer;
begin
for I := 0 to FormMain.ComponentCount - 1 do
begin
if FormMain.Components[I] is TLabel then
begin
(FormMain.Components[I] as TLabel).OnMouseEnter
:= @CustomGenericMouseEnter;
end;
if FormMain.Components[I] is TButton then
begin
(FormMain.Components[I] as TButton).OnMouseEnter
:= @CustomGenericMouseEnter;
end;
if FormMain.Components[I] is TEdit then
begin
(FormMain.Components[I] as TEdit).OnMouseEnter
:= @CustomGenericMouseEnter;
end;
end;
end;
procedure TFormMain.CustomGenericMouseEnter(Sender: TObject);
begin
SingleCustomProcedure; // no arguments, nor return value
end;
Motivation
I am programming a color picker application and thus want to show the user the mouse coordinates.
I have a Polling timer in there, I don't want to add more code, than necessary, so I hope this is self-explanatory:
procedure TFormMain.TimerMousePollTimer(Sender: TObject);
begin
if MousePosChanged then
begin
LabelEdit_MousePosX.Text := MousePosX.ToString;
LabelEdit_MousePosY.Text := MousePosY.ToString;
end;
end;
Further, I do have OnMouseLeave implemented.
TApplication(Events).OnMessage
and handleWM_MOUSEMOVE
messages? You can retrieve theTControl
under the mouse by using theGetMessagePos()
andFindDragTarget()
functions. – Remy Lebeau