当我在自己的OnClick处理程序中销毁按钮时,为什么程序崩溃? [英] Why does my program crash when I destroy a button in its own OnClick handler?

查看:187
本文介绍了当我在自己的OnClick处理程序中销毁按钮时,为什么程序崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从网站上尝试了一个脚本,我运行
http:// www .delphi-central.com / runtime.aspx 并成功。

I tried a script from a web site I run 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;

但是,如果我更改OnClick,

But if I change the OnClick,

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

它会生成错误消息。
这怎么可能发生... ???

it will generate an error message. How could this happen ...???

推荐答案

事件处理程序由控件对象的函数调用,并且事件处理程序可以有更多代码执行完成如果您删除控件,则引用该对象的任何代码可能会引起访问冲突。

An event handler is called by a function on the control's object, and it could have more code to execute once the event handler finishes. If you delete the control, then any code that references that object is likely to raise an access violation.

您需要做的是让程序删除控件 after ,它已经完成了当前运行的所有代码。为此,您需要发布消息。如果您不了解消息,这是一个很好的学习机会。

What you need to do is get your program to delete the control after it's done with all the code it's currently running. For that, you need to post a message. If you don't know about messages, this is a good opportunity to learn.

您需要创建一个新的消息类型ID。应该运行 WM_USER + 1 其中一个参数将是要删除的控件的地址。在表单上设置一个处理该消息类型的消息处理程序,并释放消息参数中引用的控件。然后在事件处理程序中,将PostMessage的消息传递给您的表单。这应该可以不导致访问冲突。

You need to create a new message type ID. WM_USER + 1 should work. One of the params will be the address of the control to be deleted. Set up a message handler on your form that handles that message type and frees the control referenced in the message param. And then in the event handler, have it PostMessage that message to your form. That should work without causing access violations.

这篇关于当我在自己的OnClick处理程序中销毁按钮时,为什么程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆