首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 遞歸遍歷視窗所有控件:通用函數 GetCtrls 實現與應用

     編輯:Delphi

在 Delphi 中動態檢查、操作視窗上的所有控件(包含巢狀容器內的子控件)是常見需求。本文提供一個通用遞歸函數 GetCtrls,能完整遍歷任意 TWinControl 及其子孫控件,並輸出控件名稱列表。

核心函數

function GetCtrls(Control: TWinControl; List: TStringList): Boolean;
var
  I: Integer;
  Child: TWinControl;
begin
  Result := False;
  if Control = nil then Exit;

  for I := 0 to Control.ControlCount - 1 do
  begin
    Child := TWinControl(Control.Controls[I]);
    List.Add(Child.Name);  { 記錄控件名稱 }

    { 若為容器控件,遞歸遍歷其子控件 }
    if Child.ControlCount > 0 then
      GetCtrls(Child, List);
  end;
  Result := True;
end;

調用範例

procedure TForm1.Button1Click(Sender: TObject);
var
  List: TStringList;
begin
  List := TStringList.Create;
  try
    GetCtrls(Self, List);  { Self = 當前表單 }
    ShowMessage(List.Text);  { 顯示所有控件名稱,含巢狀子控件 }
  finally
    List.Free;
  end;
end;

關鍵點說明

  1. 遞歸終止條件:ControlCount = 0 時不再遞歸,天然結束。
  2. 類型轉換:Controls[I] 返回 TControl,轉為 TWinControl 才能存取 ControlCount/Controls。若確定只有 TWinControl 子類可直接轉型;嚴謹代碼可加 if Controls[I] is TWinControl then 守衛。
  3. 列表所有權:調用者創建/釋放 TStringList,函數僅負責填充。
  4. 順序:深度優先、Z-Order 順序(Controls[0] 為最底層)。

進階擴展:過濾特定類型

function GetCtrlsOfType(Control: TWinControl; List: TStringList; TargetClass: TClass): Boolean;
var
  I: Integer;
  Child: TControl;
begin
  Result := False;
  if Control = nil then Exit;

  for I := 0 to Control.ControlCount - 1 do
  begin
    Child := Control.Controls[I];
    if Child.InheritsFrom(TargetClass) then
      List.Add(Child.Name);
    if Child is TWinControl then
      GetCtrlsOfType(TWinControl(Child), List, TargetClass);
  end;
  Result := True;
end;

// 使用:僅收集所有 TEdit
var Edits: TStringList;
GetCtrlsOfType(Self, Edits, TEdit);

應用場景

  • 表單驗證:遍歷所有 TEdit/TComboBox 檢查必填項。
  • 動態多語言:遍歷所有帶 Caption/Text 屬性的控件載入翻譯。
  • 狀態保存/還原:遞歸收集控件屬性值至 JSON/INI。
  • 運行時檢查:尋找重名控件、未設定 TabOrder 等問題。

效能提示

  • 控件樹通常較淺(< 10 層),遞歸開銷可忽略。
  • 頻繁調用時可將結果緩存,僅在控件結構變更時重建。
  • 大量控件(> 1000)建議改用迭代器模式避免棧溢位風險(極少見)。

這個簡單的遞歸函數是 Delphi 視窗元編程的基礎工具,掌握後可輕鬆實現各種批量控件操作需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved