Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

events

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?

like image 802
Kromster Avatar asked Aug 01 '11 08:08

Kromster


1 Answers

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.

like image 182
Nat Avatar answered Sep 30 '22 06:09

Nat