开发者

Delphi: How to assign Click event to object's method?

i have a menu item, and i'm trying to assign its OnClick event handler:

miFrobGizmo.OnClick := {something};

The OnClick event handler property, like almost every other event handler, is defined as a TNotifyEvent method type:

property OnClick: TNotifyEvent 

where TNotifyEvent is:

TNotifyEvent = procedure(Sender: TObject) of object;

i have an object, with a method matching the TNotifyEvent signature:

TAnimal = class(TObject)
public
   procedure Frob(Sender: TObject);
end;

So i think i should be able to take the method of the object and assign it to the clic开发者_JS百科k event handler:

var
   Animal: TAnimal;


miFrobGizmo.OnClick := Animal.Frob;

Except i get the error:

[Error]File.pas(1234): Not enough actual parameters

Perhaps i'm having a brain fart, but i thought i should be able to do this.


A detail i failed to mention is that my object that has the matching method is having the method exposed though an interface:

IAnimal = interface
   procedure Frob(Sender: TObject);
end;

TAnimal = class(TInterfacedObject, IAnimal)
public
   procedure Frob(Sender: TObject);
end;

var
   Animal: IAnimal;

miFrobGizmo.OnClick := Animal.Frob;

Follow-up question

If this won't work, what will?


You can't do that. It says "procedure of object", not "procedure of interface". It would let you do that if you were using an object directly, but since you're not, it doesn't consider that you're trying to assign the event handler and instead the parser tries to treat your code as a method call. Then it sees that you don't have any parameters for your method call, but the call requires one parameter so it gives up and gives you an error message.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜