PDA

View Full Version : Event handler won't assign!?



FusionWolf
30-10-2009, 02:20 AM
Hi! I was wondering why...




type
TMyEvent = procedure(Sender: TObject) of object;

TBaseClass = class
private
fOnClick: TMyEvent;
public
property OnClick: TMyEvent read fOnClick write fOnClick;
end;

{$M+}
TDescentClass = class(TBaseClass)
private
fClicked: Boolean;
public
constructor Create;
published
procedure DoClick(Sender: TObject);
end;
{$M-}

implementation


constructor TDescentClass.Create;
begin
fClicked := False;
Onclick := DoClick(Self);
end;

procedure TDescentClass.DoClick(Sender: TObject);
begin
Sender.fClicked := True;
end;


... this doesn't compile!?! It says: [DCC Error] Test.pas(312): E2010 Incompatible types: 'TMyEvent' and 'procedure, untyped pointer or untyped parameter'...

...and colors with red the line where I try to assign published method to object variable.

If I change the Create method like this:


constructor TDescentClass.Create;
var
Method: TMethod;
begin
fClicked := False;
Method.Data := Pointer(Self);
Method.Code := MethodAddress('DoClick');
Onclick := TMyEvent(Method);
end;


Then it compiles fine and method works perfectly!!

Where might be a problem? Why I cannot assign object method to event handler?

User137
30-10-2009, 01:40 PM
Try changing
Onclick := DoClick(Self);
into
Onclick := DoClick;

You are supposed to pass a pointer to procedure, not result of procedure (functions give results, procedures even don't).

FusionWolf
30-10-2009, 05:00 PM
Yes, that works! Thanks User137!! ;)

The solution was so obvious. Maybe I had too much continous coding on behind because I didn't see it myself.

Thanks again anyway even that the other solution was also fine for me. :)