Most event handlers—OnClick
included—are of type TNotifyEvent (see Listing 1).
Their first parameter is Sender, which tells
which object triggered the event. When you click a TButton,
the Sender parameter will refer to the button
object.
Listing 1
Delphi’s standard event-handler type
type
TNotifyEvent = procedure(Sender: TObject) of object;
To use the parameter, you will probably need to type cast it to the
real type of the object: TButton(Sender). When
the same event handler is assigned to objects of varying types, use the
is and as
operators to check the type of the sender.
Sometimes, the object that triggers an event isn’t really the
object of interest. In a TPopupMenu’s
OnPopup event, for instance, you often want to
know which control was clicked, not which menu is popping up. You can use
the TPopupMenu.PopupComponent property for
that.
Other times, a TAction’s
OnExecute event might fire, and you want to know
whether it was a menu item or a toolbar button that the user just
activated. TAction does not provide an easy way of attaining
that information, but it’s not supposed to. TAction is
designed to help separate functions of the program from the user
interface. If a button and a menu item don’t perform
identical operations, then they should not share an action, at
least not its OnExecute event. Instead, they
should have separate OnClick handlers. Those
event handlers should then call a third method that performs operations
common between the two UI elements.