Is there any way to get all the controls on a container control?

后端 未结 6 448
小蘑菇
小蘑菇 2020-12-10 04:11

I\'ve got a form with a bunch of controls on it, and I wanted to iterate through all the controls on a certain panel and enable/disable them.

I tried this:



        
6条回答
  •  醉梦人生
    2020-12-10 04:43

    This one finds all controls, also nested in frames etc, and points to them via the list. Be aware to free the list afterwards.

    Function AllControls(form : tForm) : tList;
    Procedure Add(Control : tControl );
    var i : integer;
    begin
      if Control is TWinControl then
      with TWinControl(Control) do
      for i := 0 to Controlcount-1 do
        Add(Controls[i]);
    
        if Control <> form  then
        result.Add(Control);
      end;
     begin
       result := tlist.create;
       add(form);
     end;
    
     var contrls : tlist;
         c : tcontrol;
     begin
        try
          contrls := AllControls(form1);
          for c in ctrls do Visit(c);  // Do something
        finally
          contrls.free;
        end;
     end;
    

    And if you want a generic version, where you can ask for a specific control type, you can use this:

    Procedure TForm1.Addcontrols( control : tcontrol; list : tlist);
    var i : integer;
    begin
      if control is twincontrol then
      with twincontrol(control) do
        for i := 0 to controlcount-1 do
        addControl(controls[i], list);
        list.Add(control)
    end;
    
    Function TForm1.GetControls(f : tform) : tlist;
    var list : tlist;
        c : tcontrol;
    begin
      list := tlist.Create;
      addControls(f, list);
      result := tlist.create;
      for c in list do
      if c <> f  then
      if c is t then
      result.Add(c);
      list.free;
    end;
    
    procedure TForm1.FormCreate(Sender: TObject);
    VAR List : TList;
    begin
      List := GetControls(self);
    end;
    
    end.
    

    Use

      List := GetControls(self);
    

    to get all controls..

提交回复
热议问题