读书人

怎样在程序中遍历某form有caption的控

发布时间: 2012-03-07 09:13:51 作者: rapoo

怎样在程序中遍历某form有caption的控件,并将它们的caption加入到listbox1里面?
怎样在程序中遍历某form有caption的控件,并将这些有caption的控件的caption加入到listbox1里面?(这些控件包括有label、button、checkbox等等,不包括edit等)
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TLabel then
listbox1.Items.Add((Components[i] as TLabel).Caption);
if Components[i] is Tbutton then
listbox1.Items.Add((Components[i] as Tbutton).Caption);
end;
end;
这段代码是分开一种一种的控件来添加,能否一次性添加,不用分哪种控件?

[解决办法]
implementation
uses TypInfo;
{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
propinfo: PPropInfo;
var
i: Integer;
begin
for i := 0 to ComponentCount - 1 do
begin
PropInfo := GetPropInfo(Components[i].ClassInfo, 'Caption ');
if propinfo <> nil then
listbox1.Items.Add(GetStrProp(Components[i], 'Caption '));
end;
end;

[解决办法]
Caption属性其实Control上就有了,就是protected而已。

type
TMyControl = class(TControl)
end;

procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
for i := 0 to ControlCount - 1 do
listbox1.Items.Add(TMyControl(Controls[i]).Caption);
end;

读书人网 >.NET

热点推荐