给你一个较全面的解决方案:
=========================
{ 1.如下函数来自我的函数库,是一个通用且稳定的动态创建函数 }
//动态创建一个可视组件.
Function GetAComp( OwnerName : Tcomponent;
CompType : TControlClass;
CompName : String;
X,Y,W,H:Integer) : TControl;
begin
if (OwnerName.FindComponent(Compname) <> nil) and
not(OwnerName.FindComponent(Compname) is TControl)
then begin Result := Nil
exit
end;
Result := OwnerName.FindComponent(CompName) as TControl;
if Result = Nil
then
begin
Result := CompType.Create(OwnerName);
with Result do
begin
if OwnerName is TwinControl then
begin
SetBounds(X,Y,W,H);
Parent := TwinControl(OwnerName);
{ 如果是可视构件,则显示之 }
if OwnerName is TForm
then TForm(OwnerName).ActiveControl := TWinControl(Result);
{ 设置窗口焦点 }
end;
end;
Result.Name := CompName;
end
else { Result <> Nil }
if not(Result is CompType)
then begin Result := Nil
Exit
end;
Result.Visible := True;
end;
{ 2.对于未知数量的控件组,可采用建立动态数组的方法,但在Delphi3中
只支持在函数参量中使用动态数组,听说D4已可构造动态数组,但我
没有用过。下面的方法利用了Tlist和类类型来实现了你的需求}
//利用TList
//=========
var ControlList : Tlist;
CreateNum : integer;
const CreateClass : TControlClass = TButton;
// 你可以任意修改TControlClass = TEdit或TPanel等。效果一样。
procedure TForm1.Button1Click(Sender: TObject);
var i:integer
p : Pointer;
begin
ControlList := TList.Create;
ControlList.Clear;
CreateNum := 10;
for i:=1 to CreateNum do
begin
p := Pointer(GetAComp(self,CreateClass,'TestB' + IntToStr(i),0,i * 20 + 1,60,20))
//创建
ControlList.add(p);
end;
end;
Procedure TForm1.Button2Click(Sender: TObject);
var i : integer;
begin
With ControlList do
for i := Count - 1 DownTo 0 do
begin TControl(items).Destroy
Delete(i)
end;
//释放
CreateNum := 0;
end;