程序中动态生成控件的方法分为三步,首先,定义生成的控件类型,再用Create函数生成控件,最后对控件的相关属性赋值。以TButton控件为例,步骤如下:
---- a. 定义控件类型
var
Button1:TButton;
---- b.生成控件
Button1:=TButton. Create(self);
Button1.Parent:=Self;
//一般将其父控件设置为Self,如果不设置Parent的值,
则控件不会在屏幕
//显示出来
---- c.设置其它属性及定义相关事件响应函数,如Caption,Left,Top,Height,Width,Visible,Enabled,Hint和onClick事件响应函数等。
//这里有一个子过程,后面付例子,一看就明白
//Designed by Quark
unit EXPro_WinControls;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ComCtrls, ExtCtrls, Grids;
//动态创建控件
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;
end.