在所述对象调用的事件期间销毁对象 [英] Destroy object during event called by said object

查看:34
本文介绍了在所述对象调用的事件期间销毁对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮.它的OnClick事件调用了一个破坏按钮的过程,但是线程"想要返回到OnClick事件,并且出现访问冲突.

I have a button. Its OnClick event calls a procedure which destroys the button, but then the "thread" wants to return to the OnClick event and I get an access violation.

我完全迷住了!

推荐答案

您需要在按钮的所有代码执行完毕后销毁按钮.执行此操作的标准方法是将用户定义的消息发布到表单,然后为表单提供一个可以解释它的message方法.例如:

You need to destroy the button after all its code is finished executing. The standard way to do this is by posting a user-defined message to the form and giving the form a message method that will interpret it. For example:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

const
  WM_KILLCONTROL = WM_USER + 1;

type

  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    procedure KillControl(var message: TMessage); message WM_KILLCONTROL;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
begin
  PostMessage(self.Handle, WM_KILLCONTROL, 0, integer(Button1))
end;

procedure TForm1.KillControl(var message: TMessage);
var
  control: TControl;
begin
  control := TObject(message.LParam) as TControl;
  assert(control.Owner = self);
  control.Free;
end;

end.

之所以起作用,是因为该消息被放入Windows消息队列中,并且直到它之前的所有内容(包括该按钮当前正在响应的Click消息)都完成处理后才会发出.

This works because the message gets put into the Windows Message Queue and doesn't come out until everything before it (including the Click message that the button is currently responding to) is finished processing.

这篇关于在所述对象调用的事件期间销毁对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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