如何更改窗体上所有控件的标题? [C++ 生成器]

How to change the caption of all controls on a form? [C++ Builder]

我想为所有控件(Tlabel、Tbutton、Teditlabel、Tbitbtn、TGroupBox 等)和所有具有来自语言文件的标题的组件(TMenuItems、TActions)设置标题。

我的问题是 TComponent、TControl 甚至 TWinControl 中的 Caption 不是 public。更重要的是,一些 'common' 控件,如 TLabel/TBitBtn 甚至不是从 TWinControl 派生的。

示例:

void SetCaptionAll(TComponent *container)
{
   for (int i = 0; i < container->ComponentCount; i++)
      {
      TComponent *child = container->Components[i];
      child->Caption = ReadFromFile;    <-- This won't work. Caption is private
      }
}

最重要的是:我不想使用宏(我认为这就是所谓的),例如:

#define GetCtrlCaption(p)\
{ code here }

因为这是不可调试的。

我需要 C++ Builder 示例,但是 Delphi 也被接受了。

适用于所有 TControl 后代:

 for i := 0 to ControlCount - 1  do
    Controls[i].SetTextBuf('CommonText');

要遍历所有控件,包括子面板中的控件,您可以使用递归遍历:

procedure SetControlText(Site: TWinControl; const s: string);
var
  i: Integer;
begin
  for i := 0 to Site.ControlCount - 1  do begin
     Site.Controls[i].SetTextBuf(PWideChar(s));
     if Site.Controls[i] is TWinControl then
       SetControlText(TWinControl(Site.Controls[i]), s);
  end;
end;

begin
   SetControlText(Self, 'CommonText');

对于像 TMenuItems 这样的组件,你可以使用 RTTI - 检查组件是否有像 Caption, Text 这样的 属性 等并设置新字符串。

Delphi 使用旧式方法的 RTTI 示例(新的 RTTI 自 D2010 起可用)。不确定 works for Builder

 uses... TypInfo

 if IsPublishedProp(Site.Controls[i], 'Caption') then
   SetStrProp(Site.Controls[i], 'Caption', 'Cap');