Board index » delphi » OnClick + (Sender: TObject) ??

OnClick + (Sender: TObject) ??

"...
 TForm = class(TScrollingWinControl)
...
published
  property OnClick;
..."
Delphi does this
procedure TForm1.FormClick(Sender: TObject);

where did
"(Sender: TObject)"
come from?

I can't do that in "my" classes,
can I?
Sender is very handy to have around.

--
"... Think what you'll know, tomorrow."
MIB

 

Re:OnClick + (Sender: TObject) ??


Quote
Donald Cameron wrote:
> "...
>  TForm = class(TScrollingWinControl)
> ...
> published
>   property OnClick;
> ..."
> Delphi does this
> procedure TForm1.FormClick(Sender: TObject);

> where did
> "(Sender: TObject)"
> come from?

> I can't do that in "my" classes,
> can I?
> Sender is very handy to have around.

You can send everything you want to an event.

{--------------------}
type
  TMyEvent: procedure(Sender: TObject) of object; {= TNotifyEvent}

  TMyClass = class
  private
    fMyEvent: TMyEvent;
  protected
    procedure DoMyEvent;
  public
    procedure Action;
    property OnMyEvent: TMyEvent read fMyEvent write fMyEvent;
  end;

  procedure TMyClass.DoMyEvent;
  begin
    { Here goes the "Sender" }
    if Assigned(fMyEvent) then fMyEvent(Self);
  end;

  procedure TMyClass.Action;
  begin
    DoMyEvent;
  end;
{--------------------}

-ThomasN

Re:OnClick + (Sender: TObject) ??


In article <ffIE5.314315$Gh.9145...@news20.bellglobal.com>, "Donald Cameron"

Quote
<came...@sympatico.ca> writes:
>Delphi does this
>procedure TForm1.FormClick(Sender: TObject);

>where did
>"(Sender: TObject)"
>come from?

Because the event handler is of a standard type (TNotifyEvent), and to prevent
having to have a different event type for every object which might be "sent",
the parameter of the event handler is declared as having the "simplest" object
(ie of the most ancestral type). Then any descendant of that parameter type can
be used as a parameter (because any descendant must include the capabilities of
a TObject).

However the downside of this facility is that the compiler thinks of it _as_ a
TObject and hence thinks it does not have the properties and methods of the
object which is actually specified as the parameter. Hence it will not allow
access to such properties and methods. So you must typecast it to the actual
object (or to one which has the property of method which you want to use.

But if there is a possibility that an object "simpler" than your typecast
object might be passed as a parameter, then a type check should be included.
There are a couple of ways to do this :-

// Simple typecast - GPF if Sender is not TListBox or descendant
  MyVar := TListBox(Sender).ItemIndex;

// raise exception if Sender is not TListBox or descendant
  try
    MyVar := (Sender as TListBox).ItemIndex;
  except
   // handle exception
  end;

// do nothing if Sender is not TListBox or descendant
  if (Sender is TListBox) then
    MyVar := TListBox(Sender).ItemIndex;

Alan Lloyd
alangll...@aol.com

Other Threads