您的位置:首页 > 编程语言 > Delphi

Delphi动态创建、删除按钮

2020-02-03 01:13 961 查看

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.

  • 点赞
  • 收藏
  • 分享
  • 文章举报
站内首发文章 shen_jiaqiang 发布了59 篇原创文章 · 获赞 0 · 访问量 2918 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: