新開一個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.
作者:lzcx