Why does my program crash when I destroy a button in my OnClick handler?

I tried the script from a website that I ran http://www.delphi-central.com/runtime.aspx and succeed.


private
  { Private declarations }
  procedure CustomButtonClick(Sender: TObject);

procedure TForm1.AddNewButtonClick(Sender: TObject);
var
  NewButton : TButton;
begin 
  NewButton := TButton.create(self);

  with NewButton do
  begin
    Top    := 30;
    Width  := 60;
    Left   := Width * (self.ControlCount-2);
    Parent := self;
    OnClick := CustomButtonClick;
    Caption := 'Button '+ inttostr (self.ControlCount-2);
  end;  //With
end;

procedure TForm1.DeleteLastButtonClick(Sender: TObject);
begin
  if Self.ControlCount>2 then
    TButton (Controls[ControlCount-1]).destroy;
end;

procedure TForm1.CustomButtonClick(Sender: TObject); 
begin    
    ShowMessage(TButton(Sender).caption + ' Pressed'); 
end;

But if I changed OnClick,

OnClick := CustomButtonClick; ==> OnClick := DeleteLastButtonClick;

it gives an error message. How could this happen...???

+5
source share
3 answers

The event handler is called by the function of the control object, and it may have more code to execute after the event handler completes. If you remove the control, then any code that refers to this object can cause access violation.

, , , . . , .

. WM_USER + 1 . , . , , , . PostMessage . .

+6

, - , , , .

, .

, , , CustomButtonClick !

+5

, , - / . , .

, - , onClick .

+1

All Articles