1

如果我TButton使用此例程创建多个对象:

procedure CreateButton;
begin
  Btn := TButton.Create(nil);
end;

然后,我如何引用特定对象实例以使用另一种方法释放它,例如:

procedure FreeButton;
begin
  Btn[0].Free;  //???
end;

当然,这不会编译,但我认为问题很明确:我如何声明Btn?以及如何释放多个实例?

4

1 回答 1

1

TButton创建一个不属于表单的任何地方(您的代码会这样做)没有多大意义。

话虽如此,为了稍后引用它以释放它,您需要在某处存储对它的引用。

由于您指的是“多个按钮”并在您的删除例程中使用数组代码,我认为您可能想要跟踪一组按钮。这是一个这样做的例子:

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);   // Add via Object Inspector Events tab
  private
    { Private declarations }
    // Add these yourself
    BtnArray: array of TButton;
    procedure CreateButtons(const NumBtns: Integer); 
    procedure DeleteBtn(BtnToDel: TButton);
    procedure BtnClicked(Sender: TObject);  
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.DeleteBtn(BtnToDel: TButton);
var
  i: Integer;
begin
  // Check each button in the array to see if it's BtnToDel. If so,
  // remove it and set the array entry to nil so it can't be deleted
  // again.
  for i := Low(BtnArray) to High(BtnArray) do
  begin
    if BtnArray[i] = BtnToDel then
    begin
      FreeAndNil(BtnArray[i]);
      Break;
    end;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  // Create 10 buttons on the form
  CreateButtons(10);
end;

// Called when each button is clicked. Assigned in CreateButtons() below    
procedure TForm1.BtnClicked(Sender: TObject);
begin
  // Delete the button clicked
  if (Sender is TButton) then
    DeleteBtn(TButton(Sender));
end;

procedure TForm1.CreateButtons(const NumBtns: Integer);
var
  i: Integer;
begin
  // Allocate storage for the indicated number of buttons
  SetLength(BtnArray, NumBtns);

  // For each available array item
  for i := Low(BtnArray) to High(BtnArray) do
  begin
    BtnArray[i] := TButton.Create(nil);              // Create a button
    BtnArray[i].Parent := Self;                      // Tell it where to display
    BtnArray[i].Top := i * (BtnArray[i].Height + 2); // Set the top edge so they show
    BtnArray[i].Name := Format('BtnArray%d', [i]);   // Give it a name (not needed)
    BtnArray[i].Caption := Format('Btn %d', [i]);    // Set a caption for it
    BtnArray[i].OnClick := BtnClicked;               // Assign the OnClick event
  end;
end;

如果您将此代码放入一个新的空白 VCL 表单应用程序并运行它,您将through在一个表单上看到 10 个按钮('Btn 0 Btn 9`)。单击按钮会将其从表单(和数组)中删除。

于 2013-05-10T16:24:25.580 回答