type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); private { Private declarations } procedure OnAddControl(const AControl: TControl; const ACol, ARow: Integer); public { Public declarations } end;
var Form1: TForm1;
implementation
{$R *.dfm}
// 按钮之间的间距 const RowSpace = 8; ColSpace = 8;
type TAddControlEvent = procedure(const AControl: TControl; const ACol, ARow: Integer) of object;
procedure CreateControls(AOwner: TWinControl; const R: TRect; const ACol, ARow: Integer; AClass: TControlClass; OnAdd: TAddControlEvent = nil); var H, W: Integer; I, J: Integer; X, Y: Integer; Ctrl: TControl; begin if not Assigned(AOwner) then Exit; if not Assigned(AClass) then Exit; if (ARow < 1 ) or (ACol < 1) then Exit;
H := (R.Bottom - R.Top - (ARow + 1) * RowSpace) div ARow; W := (R.Right - R.Left - (ACol + 1) * ColSpace) div ACol; if (H < 1) or (W < 1) then Exit;
for I := 0 to ARow - 1 do for J := 0 to ACol - 1 do begin Ctrl := AClass.Create(AOwner); with Ctrl do begin Parent := AOwner; X := (J + 1) * ColSpace + J * W; Y := (I + 1) * RowSpace + I * H; BoundsRect := Rect(X, Y, X + W, Y + H);
if Assigned(OnAdd) then OnAdd(Ctrl, J, I); Show; end; end; end;