//动态创建控件
function DynaCreateComponent(OwnerName: TComponent; CompType: TControlClass; CompName: String; V_Left,V_Top,V_Width,V_Height:Integer): TControl;
implementation
function DynaCreateComponent(OwnerName: TComponent; CompType: TControlClass; CompName: String; V_Left,V_Top,V_Width,V_Height: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(V_Left,V_Top,V_Width,V_Height);
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;
{对于未知数量的控件组,利用TList
var ControlList: Tlist; CreateNum: integer;
const CreateClass : TControlClass = TButton;//可以任意修改TControlClass = TEdit或TPanel等。效果一样。
var i:integer; V_Point: Pointer;
ControlList := TList.Create;
ControlList.Clear;
CreateNum := 10;
for i:=1 to CreateNum do
begin
V_Point := Pointer(DynaCreateComponent(self,CreateClass,'Button_' + IntToStr(i),0,i*20+1,60,20));//创建
ControlList.Add(V_Point);
end;
TButton(ControlList.Items[i]).Caption := 'XXXX';}
end;