如何在每两个不同的类上一起触发事件
Posted
技术标签:
【中文标题】如何在每两个不同的类上一起触发事件【英文标题】:How to trigger the event together on each two deferent class 【发布时间】:2011-02-25 19:59:12 【问题描述】:我在一个单元上有两个对象类,是否可以触发这两个事件?假设触发了 FIRSTCLASS 事件,那么 SECONDCLASS 也会触发吗?
假设......
//Class 1-------------------------------------------------------------
type
TOnEventTrigger = procedure(Sender : Tobject; Value :integer);
TMyFirstClass = Class(Tcomponent)
private
....
public
....
propert OnEventTrigger : TOnEventTrigger read Fevent write Fevent;
end;
procedure TMyFirstClass.FEvnt(Sender : Tobject; Value :integer);
begin
// here is normaly triggers the event //
if Assigned(OnEventTrigger) then
OnEventTrigger(Self,FSomevalue);
// POSTMessage(GetForegroundWindow,WM_USER+3,0,0);
// this is what i did here to get the result of FSomevalue
// but this is not ideal. It work only on focus window.
end;
//Class 2-------------------------------------------------------------
type
TOnEventTrigger = procedure(Sender : Tobject; Value :integer);
TMySecondClass = Class(Tobject)
private
....
public
....
property OnEventTrigger : TOnEventTrigger; read Fevent write Fevent;
end;
procedure TMySecondClass.FEvnt(Sender : Tobject; Value :integer);
begin
// I wanted here to trigger, whenenver the above is fired //
if Assigned(OnEventTrigger) then
OnEventTrigger(Self,FSomevalue);
end;
【问题讨论】:
【参考方案1】:您可以在创建两个类时将相同的事件处理程序分配给它们(伪代码):
Form1 = class()
private
...
protected
A : TMyFirstClass;
B : TMySecondClass;
procedure MyHandler(Sender: TObject; Value: Integer);
end;
procedure Form1.CreateForm();
Begin
Create A & B
A := TMyFirstClass.Create(Self);
B := TMySecondClass.Create(Self);
Assign Event Handler to both classes
A.OnEventTrigger := MyHandler;
B.OnEventTrigger := MyHandler;
End;
procedure Form1.MyHandler(Sender: TObject; Value: Integer);
Begin
ShowMessage('Event from '+Sender.ClassName+'. Value='+IntToStr(Value));
End;
这样,当事件从任一类触发时,它都会在 MyHandler() 代码中结束。
【讨论】:
以上是关于如何在每两个不同的类上一起触发事件的主要内容,如果未能解决你的问题,请参考以下文章