【发布时间】:2012-03-05 03:56:39
【问题描述】:
我创建了一个继承自 THTTPReqResp 的自定义组件 TCustomHTTPReqResp。
我还为此组件创建了一个自定义事件。我遇到的唯一问题是,虽然事件已发布并出现在 IDE 上,但当我分配事件处理程序并运行应用程序时,不会调用事件处理程序。
但是,如果在 Form.Create 上的代码上分配它,即:
CustomHTTPReqResp1.OnBeforeGet := CustomHTTPReqResp1BeforeGet;
它有效。除此之外,其他一切都很好。
做错了什么?提前致谢。
这是自定义组件的代码:
unit CCustomHTTPReqResp;
interface
uses
SysUtils, Classes, Dialogs, SOAPHTTPTrans;
type
TCustomHTTPReqResp = class(THTTPReqResp)
private
{ Private declarations }
FOnBeforeGet: TNotifyEvent;
procedure DoOnBeforeGet;
protected
{ Protected declarations }
procedure SetOnBeforeGet(const AOnBeforeGet: TNotifyEvent);
public
{ Public declarations }
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure Get(Resp: TStream); override;
published
{ Published declarations }
{ Events }
property OnBeforeGet: TNotifyEvent read FOnBeforeGet write SetOnBeforeGet;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('My Components', [TCustomHTTPReqResp]);
end;
{ TCustomHTTPReqResp }
constructor TCustomHTTPReqResp.Create(Owner: TComponent);
begin
inherited Create(Owner);
// Code here.
end;
destructor TCustomHTTPReqResp.Destroy;
begin
// Code here.
inherited;
end;
procedure TCustomHTTPReqResp.SetOnBeforeGet(const AOnBeforeGet: TNotifyEvent);
begin
FOnBeforeGet := AOnBeforeGet;
end;
procedure TCustomHTTPReqResp.DoOnBeforeGet;
begin
if Assigned(FOnBeforeGet) then
begin
FOnBeforeGet(Self);
end
else
begin
MessageDlg('No Before Post Event Handler found!', mtInformation, mbOKCancel, 0);
end;
end;
procedure TCustomHTTPReqResp.Get(Resp: TStream);
begin
// Raise OnBeforeGet.
DoOnBeforeGet;
inherited Get(Resp);
end;
end.
【问题讨论】:
-
对我来说看起来不错。我看不出你发布的代码有什么问题。
-
代码没有问题;事件正在被触发(在 D2009 上确实经过测试)。只需一个题外话 - 在这种情况下,您不需要
FOnBeforeGet的设置器,因此您可以保存SetOnBeforeGet并直接使用property OnBeforeGet: TNotifyEvent read FOnBeforeGet write FOnBeforeGet;
标签: delphi events event-handling delphi-2009 custom-component