Connaître l'arborescence de composants dans une fiche

Il peut parfois arriver d'avoir besoin de connaître l'arborescence des composants présents dans une fiche FireMonkey. Pour cela c'est assez simple puisque chaque composant a une propriété ChildrenCount qui indique combien il a d'enfants et une propriété Children qui contient ses enfants.

Ce bout de code permettra d'afficher l'arborescence de la fiche actuelle dans un TMemo :

procedure TForm1.FormCreate(Sender: TObject);

  procedure godown(o: tfmxobject; indent: string = '');
  var
    c: tfmxobject;
  begin
    if assigned(o) then
    begin
      Memo1.Lines.Add(indent + '> ' + o.ClassName);
      if (o.ChildrenCount > 0) then
        for c in o.Children do
          godown(c, indent + '--');
    end;
  end;

begin
  Memo1.Lines.Clear;
  godown(self);

  if (application.ComponentCount > 0) then
    for var i := 0 to application.ComponentCount - 1 do
      if (application.Components[i] is tfmxobject) then
        godown(application.Components[i] as tfmxobject);
end;

Ce qui donne ça pour un écran avec un TStyleBook, un TStringGrid et un TMemo :

> TForm1
--> TStringGrid
----> TStyledGrid
------> TCellText
----> TGridScrollContent
------> TStringColumn
------> TCheckColumn
------> TDateColumn
--> TMemo
----> TFixedStyledMemo
----> TScrollContent
--> TStyleBook

Bien entendu on peut en faire plein de choses et l'étendre à l'intégralité des fiches de l'application si on pioche dans Application.Components pour y trouver tout ce qui une TForm ou plus simplement un TFMXObject.

Par exemple avec :

  if (application.ComponentCount > 0) then
    for var i := 0 to application.ComponentCount - 1 do
      if (application.Components[i] is tfmxobject) then
        godown(application.Components[i] as tfmxobject);

Mug carte postale SydneyMug Pascal case in Alexandrie