Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

How to check if two events are pointing to the same procedure in Delphi?

Say I have a Button1.OnClick event linked to Button1Click procedure. I also have Button2.OnClick linked to some other procedure. How do I check that both events are linked to different or same procedure from runtime?

I tried to test if:

  • Button1.OnClick = Button2.OnClick, but that gave me an error (Not enough actual parameters)
  • @(Button1.OnClick) = @(Button2.OnClick), error again (Not enough actual parameters)

How do I test it properly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A method reference can be broken down in to two parts, the pointer to the object and the pointer to the method itself. There is a convenient record type defined in the System unit called TMethod that allows us to do that break down.

With that knowledge, we can write something like this:

function SameMethod(AMethod1, AMethod2: TNotifyEvent): boolean;
begin
  result := (TMethod(AMethod1).Code = TMethod(AMethod2).Code) 
            and (TMethod(AMethod1).Data = TMethod(AMethod2).Data);   
end;

Hope this helps. :)

Edit: Just to lay out in a better format the problem I am trying to solve here (as alluded to in the comments).

If you have two forms, both instantiated from the same base class:

Form1 := TMyForm.Create(nil);
Form2 := TMyForm.Create(nil);

and you assign the same method from those forms to the two buttons:

Button1.OnClick := Form1.ButtonClick;
Button2.OnClick := Form2.ButtonClick;

And compare the two OnClick properties, you will find that the Code is the same, but the Data is different. That is because it's the same method, but on two different instantiations of the class...

Now, if you had two methods on the same object:

Form1 := TMyForm.Create(nil);

Button1.OnClick := Form1.ButtonClick1;
Button2.OnClick := Form1.ButtonClick2;

Then their Data will be the same, but their Code will be different.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...