[Lazarus] Assigning Class to object

R.Smith ryansmithhe at gmail.com
Mon Dec 6 01:15:33 CET 2021

 > if I call the following procedure with either a TButton or Panel ctrl 
(for example), how can I use the class info contained within the MyObj 
to choose the correct Class

Two things,

Firstly the correct way of determinig class (as with your current 
solution) is like this:

   if (MyObj is TButton) then TButton(MyObj).OnMouseDown := tmethod (not 
important here)  else
   if (MyObj is TPanel)  then TPanel(MyObj).OnMouseDown := tmethod (not 
important here)  else
   //  etc...

If you want to change a property/method of many descendants of class 
which all contain the same property, that is quite easy and what object 
orientation is great at, but you have to figure out what is the most 
recent ancestor class that is the ancestor of all the classes that you 
wish to treat similarly, AND if the property(ies) are defined in the 
ancestor or higher.  This is trivial to do just looking through the FPC 
help/documentation pages for the classes in question.

In the case you describe, from memory I believe TControl is the 
recent-most ancestor of both those classes that already has the 
OnMouseDown event defined, so this should work:

procedure SetThis( MyObj :TObject );
   TControl(MyObj).OnMouseDown := @someMouseDownMethod;


More information about the lazarus mailing list