You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RAD Studio设计器代码中获取Form所有子元素?求GetChildren用法示例

获取TCustomForm所有子元素的正确方法(基于GetChildren)

先理清GetChildren的参数与返回值

  • 第一个参数Proc: TGetChildProc:这是回调函数,每枚举到一个子控件就会触发它,你可以在这个函数里完成子控件的收集逻辑。
  • 第二个参数Root: TComponent:是传递给回调的上下文参数,通常用来传你存放子控件的容器(比如列表),不是必须传Form实例——你之前的误解在这里,它只是用来给回调传数据的载体。
  • 返回值Integer:返回本次枚举到的子控件总数。

回调函数TGetChildProc的定义是procedure(Child: TComponent; Root: TComponent);,第一个参数是当前枚举到的子控件,第二个就是你传入的上下文容器。

实际使用示例(Delphi代码)

以下是完整的可运行示例,用来收集Form的所有子控件:

uses
  Vcl.Forms, Vcl.Controls, System.Generics.Collections;

// 自定义回调:把枚举到的子控件存入列表
procedure CollectChildControls(Child: TComponent; Root: TComponent);
var
  ChildList: TList<TComponent>;
begin
  ChildList := TList<TComponent>(Root);
  // 排除Form自身,只添加子控件
  if Child <> Root then
    ChildList.Add(Child);
end;

// 在Form的按钮点击事件中调用
procedure TForm1.Button1Click(Sender: TObject);
var
  ChildControls: TList<TComponent>;
  Child: TComponent;
  TotalCount: Integer;
begin
  ChildControls := TList<TComponent>.Create;
  try
    // 调用GetChildren:传回调函数和存放结果的列表
    TotalCount := Self.GetChildren(CollectChildControls, ChildControls);
    ShowMessageFmt('共找到%d个子控件', [TotalCount]);
    // 遍历输出所有子控件名称
    for Child in ChildControls do
      Memo1.Lines.Add(Child.Name);
  finally
    ChildControls.Free;
  end;
end;

补充:只获取直接子控件的方法

如果不需要递归获取容器内的嵌套控件(比如Panel里的Button),可以直接遍历Form的Components属性,更简单:

procedure TForm1.Button2Click(Sender: TObject);
var
  i: Integer;
begin
  Memo1.Clear;
  for i := 0 to Self.ComponentCount - 1 do
    if Self.Components[i] is TControl then // 只筛选可视化控件
      Memo1.Lines.Add(Self.Components[i].Name);
end;

内容的提问来源于stack exchange,提问作者Cort

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:57:09