【IT168技术文档】
新开一个project,然后拖两个Button放在窗体上
代码如下:
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) btnAddButton: TButton; btnDeleteLast: TButton; procedure btnAddButtonClick(Sender: TObject); procedure btnDeleteLastClick(Sender: TObject); private { Private declarations } procedure CustomButtonClick(Sender: TObject); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnAddButtonClick(Sender: TObject); var NewButton: TButton; // 新 Button的指针 begin // 在内存中创建一个 Button,拥有者为self,这样当窗体 destory时,这个新button // 能够被自动释放 NewButton := TButton.Create(Self); With NewButton do begin Top := 60; // button 的出现的坐标 Width := 60; // button 的宽度 Left := Width * (Self.ControlCount - 2); Parent := Self; // 指明在那个窗体显示 OnClick := CustomButtonClick; // 指定button click事件 Caption := 'Button' + IntToStr(Self.ControlCount - 2); end; // with end; procedure TForm1.btnDeleteLastClick(Sender: TObject); begin // 确定窗体上有新的button if Self.ControlCount > 2 then // 删除最后新建的 button TButton(Controls[ControlCount - 1]).Destroy; end; procedure TForm1.CustomButtonClick(Sender: TObject); begin // 根据 Sender 来判断哪个新建的button click ShowMessage(TButton(Sender).Caption + ' Pressed'); end; end.