How can i access properties of classes by name?

How can i access properties of classes that are not implemented via the uses-clause, just knowing their names?

You have to use the TypInfo unit.

Simple properties, like strings and integer, can be accessed in the

following manner:



-------------------------------------------------------------

Uses TypInfo;



procedure AlterProp(AName, APropName, AValue:string);

var i : integer;

     C : TComponent;

begin

    // Run through all Components to find the right Component

    for i:=0 to Form1.Componentcount-1 do

    begin

        C := Form1.Components[i];

        if (C.Name = AName) then

        begin

            SetPropValue(C,APropName, AValue);

        end;

    end;

end;

-------------------------------------------------------------



Now there are also some Properties like Font. How do i reach

        those sub-properties?

Here is a solution to that:



-------------------------------------------------------------

Uses TypInfo;



procedure AlterFontColor(AName:string; AColor:TColor);

var i : integer;

     C : TComponent;

     AObj : TObject;

begin

    // Run through all Components to find the right Component

    for i:=0 to Form1.Componentcount-1 do

    begin

        C := Form1.Components[i];

        if (C.Name = AName) then

        begin

            AObj := GetObjectProp(C,'Font');


            SetPropValue(AObj,'Color',AColor);

        end;

    end;

end;

-------------------------------------------------------------



And finally you have many indexed properties like TStrings

        or stuff.

Now how do i reach those indexed properties?

All indexed properties are stored in TCollection-Objects. So

        you have to Typecast them like in the following function:



-------------------------------------------------------------

Uses TypInfo;



procedure AlterIndexObject(ACompName, APropName:string; ACaption: string);

var i : integer;

     C : TComponent;

     ACollection, AObj : TObject;

begin

    // Run through all Components to find the right Component

    for i:=0 to Form1.Componentcount-1 do

    begin

        C := Form1.Components[i];

        if (C.Name = ACompName) then

        begin

            AObj:= GetObjectProp(C,APropName);

            ACollection := TCollection(AObj).Items[0];

            SetPropValue(ACollection, 'Caption', ACaption);

        end;

    end;

end;

-------------------------------------------------------------



There are many possibilities for this functions to use in your projects.

Mainly there are usefull for language-changings or skin-components.

The possibilities are endless.

I hope my article was somewhat usefull for you.

I like to share knowledge with other developers.



keep on coding :-)



Jürgen Sommer










 

Share this article!

Follow us!

Find more helpful articles: