Delphi 每個表單對應一個 .dfm 檔案,記錄表單與控件的屬性狀態。雖然 DFM 為二進位/文字混合格式,僅在 IDE 中可視化編輯,但理解其結構後,可透過手動調整控件宣告順序,將 Controls / Components 陣列「陣列化」,大幅簡化批次操作程式碼。
DFM 以 object ... end 巢狀結構描述元件樹:
object Form1: TForm
Left = 200
Top = 100
// 先列出 TGraphicControl 類控件 (無視窗控制代碼)
object Label1: TLabel
Left = 256
Top = 80
Caption = 'Label1'
end
// 再列出 TWinControl 類控件 (有視窗控制代碼)
object Button1: TButton
Left = 50
Top = 50
Caption = 'Button1'
end
object Button2: TButton
Left = 50
Top = 90
Caption = 'Button2'
end
end
Controls[] 與 Components[] 索引Controls[] 僅包含同層級的 TWinControl 子控件Components[] 包含表單擁有的所有元件 (含非視覺元件)Button1.Enabled := False;
Button2.Enabled := False;
Button3.Enabled := False;
// ... 冗長且難維護
for I := 0 to ControlCount - 1 do
if Controls[I] is TButton then
(Controls[I] as TButton).Enabled := False;
Form1.dfmTButton 的 object ... end 區塊移至連續位置n,則第一個 Button 索引為 n-1for I := n-1 to n-1 + ButtonCount - 1 do
(Controls[I] as TButton).Enabled := False;
假設表單有 20 個 TEdit 依序對應欄位,需依序串接非空值:
Controls[] 索引為 n-1for I := n-1 to n-1 + EditCount - 1 do
begin
if (Controls[I] as TEdit).Text = '' then
begin
Application.MessageBox('請填寫必要資訊', '提示', MB_OK);
Exit;
end;
InfoStr := InfoStr + (Controls[I] as TEdit).Text;
end;
TGraphicControl (Label、Shape 等) 永遠排在 TWinControl 前,不可跨層移動Controls (同層) 與 Components (全層級)透過掌握 DFM 的有序特性,開發者可將 Delphi 原生不支援的「控件陣列」功能以零成本實現,對於大量同類控件的批次操作 (啟用/禁用、驗證、資料收集) 具有顯著的程式碼簡化與效能提升效果。此技巧適用於 Delphi 所有版本,屬於進階開發者的實用工具箱必備技能。