Return to sender
The Lowly Sender Parameter Can Make Applications SHINE
The humble Sender parameter could be one of Delphi's most useful tools for modular, extensible programming. Although Sender is normally used to simply determine which object called a particular procedure, with some creativity, this parameter can be extended to allow robust modular programming with simple, Reusable code.
Sender Basics
The Sender parameter is so ingrained in Delphi programming that it appears in practically every program procedure Even the Form's OnCreate event - which has no sender - includes the (Sender: TObject). Parameter in its definition.
Despite its ubiquity, the Sender parameter is not necessary for a procedure to function. Removing Sender from a procedure that does not use it results in perfectly functional code, as long as the parameter is also removed from the procedure's type statement in the form object's interface section. Delphi will generate an "incompatible parameter" warning at compile time, but this can be safely ignored. in fact, removing any unused Sender parameters results in slightly leaner and meaner code.
Not only can Sender be omitted from any procedure, but when used, it does not even have to be called Sender. This name is only used by convention. The common term makes understanding code simpler, but there's no reason not to name it Caller , Origin, or Banana if the developer prefers.
So the sender parameter doesn't Have To Be Called Sender, And IS, IN FACT, Unnecessary. So what is it? And why is it important enough to add to practically every Delphi Procedure?
Sender is simply a parameter passed from the component that called the event handler. Sender (or whatever it's called by the event handler) is a parameter of the type TObject. Because TObject is the ancestor of all components, Sender can accommodate any Delphi object that can possibly trigger an event Sender forms a two-way link between an object and an event handler;.. it tells the procedure what object triggered it to be called In other words, if an event handler was a letter, the Sender parameter would be The return address.using sender
THE SIMPLEST AND MOST COMMON WAY TO USE Sender is with an est ... the or case depending on what object triggered the proMpledure. Here's a type
Procedure form1.buttonclick (sender: TOBJECT);
Begin
IF sender is stopbutton
THEN STOP (Sender);
END;
This code examines the Sender parameter to see if it's the object, StopButton. If so, the event handler calls another procedure, Stop, passing the Sender parameter to that procedure as well. The Stop procedure can call another procedure and so on, passing the Sender parameter through the program code. Because each procedure is simply passing along the parameter it received, wherever the parameter is ultimately used, it will reflect the object that called the original event handler.
Not only can Delphi developers use Sender to identify the object that called a procedure, but they can also use it to access that object's properties. The form in Figure 1 uses a number of colored panels as a palette. When the user clicks on a panel , The Large Panel on The Left Change To The Color of The Selected Panel.
Figure 1:. This mini-program sets the color of the panel at right to the color of the panel selected by the user.This procedure does not need the name of the panel selected, only its color property Therefore, each panel in the palette CAN Have ITS OWN Color, But All Share The Following Onclick Event Handler:
Procedure TFORM1.Panel1click (Sender: TOBJECT);
Begin
Panel1.color: = TPANEL (Sender) .color;
END;
Since Sender provides a "return address" to the calling object, that object's properties can be read and set as well This way, the procedure can also change the panel's Color property without actually working with the panel object's name For example..:
TPANEL .COLOR: = CLRED;
Any type of property can be accessed using this framework, provided it's a property belonging to the specified type. In the previous example, the procedure specifies that Sender is a TPanel, which therefore has a Color property. While Sender is declared as a TObject in The Procedure Header, The Following Line Would Return A Compiler Error.
TPANEL1.COLOR: = TOBJECT (Sender) .color;
As TPanel's ancestor type, TObject is perfectly valid in other respects; but it does not contain a Color property Since TObject contains no properties, developers can not use it to determine the properties of a wide range of objects This means a program can not find the.. Color of a TPANEL, TLABEL, OR TFORM All with The Same Tobject (Sender) .Color Code.
In fact, these three component types all contain the Color property. However, because they do not share this property in common ancestor classes, programmers can not easily create one block of code to get the Color property from these various types of objects. The simplest solution A developer Could Use Would Be this: if sender is tpanel life
Brush.color: = TPANEL (Sender) .color;
IF sender is TLABEL THEN
Brush.color: = TLABEL (Sender) .color;
IF sender is tform dam
Brush.color: = tform (sender) .color;
Fortunately for developers, the Delphi designers added the Tag property. Tag is a little catch-all integer parameter that developers can use for whatever purpose they choose. What makes Tag especially useful is that it resides well up the inheritance tree in the TComponent class. Just two steps down the ladder from TObject, TComponent is the ancestor of all controls. This means that any of these objects will have the Tag property. Unlike the Color property cited above, the Tag property of any object can be accessed with a simple line Of code:
TFORM.TAG: = Tcomponent (sender) .tag;
Sender IMPOSTORS
I mentioned earlier that as procedures pass the Sender parameter from one to another, it never changes. It always points back to the object that called the original event handler. This is true provided each procedure along the path passes the original parameter. However, you Can Also Substitution Another Parameter for the Original Sender, Fooling Subsequent Procedures Into Acting On ANOTHER Object As if it. The true sender.
This is the basis of our sample application, SENDER.DPR. It uses Sender and the Tag property so that Delphi can be "fooled" into having similar menu and button commands perform special actions on the buttons. Traditionally, this would not require special Sender Parameters - Both Buttons and Menu Items Will Share An Event Handler That Can Update The Button As Part of Its FunctionAlity: Procedure Button1Click (Sender: Tobject);
Begin
{Main functionality}
Button1.font.style: = [fsbold];
END;
HOWEVER, WHEN Seveents Share A Single Event Handler, The Programmer Cannot Simply Assume To Act ON A Specific Object. Modifying The Code In Questions To Read:
TButton (sender) .font.style: = [fsbold];
is fine provided the code is always called by a TButton. However, this makes it troublesome to call the same event handler from a corresponding menu item because the menu item will cause an error each time it calls the event handler.
The Sample Application's Framework
The sample application provides the framework for a modular, easily-extendible application. It also demonstrates how to make the simple Sender parameter do a lot of high-powered work, and shows how to get around some of the limitations mentioned earlier.
Most applications contain menu items and buttons that perform the same action. Delphi makes it simple to do this by routing multiple events to a shared event handler. If multiple buttons and menu items all use the same event handler, it's simple to determine which control called the procedure. However, it becomes more difficult to determine, say, which menu item corresponds to the calling event if the control was actually a button. The user may obviously find that the Word Wrap button and the Word Wrap menu command are synonymous in functionality . However, to have Delphi understand this and update the menu item's Checked property - regardless of which control was the Sender - takes some special programming.The sample application contains four SpeedButtons, as well as main and pop-up menu items that correspond to each (See Figure 2). The Buttons and Menu Items Each Perform Similar Functions, in this case, using a database to TRACK THE AMOTI TIME SPENS. P Rogram Users Can Configure Any Number of Tasks, All of Which Call The Same Event Handler. (for The Sake of Clarity) Only the sender functions.) ONLY
Figure 2: The Layout of The Sample Application's Components.
While a task is active, its SpeedButton remains depressed. Pressing a depressed button releases it and ends the task. Pressing a button while another is depressed releases the first and depresses the new button, causing the timesheet database to be simultaneously updated. The trick, Of Course, Is To Handle A Number of Menuitems and Speedbuttons All with one event handler. This Technique Enables the program of tasks with allow to write a new handler for each.
Implementing this functionality requires one more ingredient:. The Components property Like Tag, Components is a property of TComponent, meaning that it's accessible to all components Components is a property of every component, but in most cases it's only used on TForms In this.. Case, The Components Property Is An Array Of All Components Owned by The Form.Build IT
To build the sample application, create a single form named Form1. Add four SpeedButtons (used here to easily allow two-state buttons), a Label, a MainMenu (with an item called File1 and four sub-items), and a pop- Up Menu (Also With Four Menu Items). Set The Properties AS Shown in Figure 3.
SpeedButtons Name / Caption AllowAllUp GroupIndex Tag OnClick event handler SpeedButton1 True 1 1 SpeedButtonClick SpeedButton2 True 1 2 SpeedButtonClick SpeedButton3 True 1 3 SpeedButtonClick SpeedButton4 True 1 4 SpeedButtonClick
MenuItems Name / Caption Tag OnClick event handler File1 0 - MainItem1 1 SpeedButtonClick MainItem2 2 SpeedButtonClick MainItem3 3 SpeedButtonClick MainItem4 4 SpeedButtonClick PopupItem1 1 SpeedButtonClick PopupItem2 2 SpeedButtonClick PopupItem3 3 SpeedButtonClick PopupItem4 4 SpeedButtonClick
Figure 3: Setting The Values of Properties for The Sample Application's SpeedButton and MenuItem Components.
Note that all the buttons and menu items have the same event handler, namely SpeedButtonClick (see Figure 4). This procedure is called from any of the SpeedButtons or menu items on (except MenuItem File1) the form. It references two external procedures, PushButton And releasebutton.
Procedure TFORM1.SPEEDBUTTONCLICK (Sender: TOBJECT);
VAR
A: Integer;
Begin
IF sender is TspeedButton Then
if TspeedButton (Sender) .down then
Pushbutton (sender) ELSE
ReleaseButton (Sender)
Else
For A: = 0 to ComponentCount-1 DO
IF Components [A] Is TspeedButton Then
With Components [A] as TspeedButton Do
If tag = tcomponent (sender) .tag dam
Begin
Down: = NOT DOWN;
IF down kil
Pushbutton (Self.components [A])
Else
ReleaseButton (Self.components [A]);
END;
END;
Figure 4: Referencing Pushbutton and releasebutton with the spesedbuttonclick procedure.
SpeedButtonClick first determines which object sent the event. If it's a TSpeedButton, it simply passes that object to the PushButton or ReleaseButton procedure, depending on the button's state (up or down). These procedures simply allow convenient spots for the messages to be handled. In The Following Example, The Caption of Label1 IS Set To Report The Event That Occurred:
Procedure TForm1.pushbutton (Sender: TOBJECT);
Begin
Label1.caption: =
Tcomponent (sender) .Name 'was click.';
END;
Procedure TFORM1.RELEASEBUTTON (Sender: TOBJECT);
Begin
Label1.caption: =
Tcomponent (sender) .Name 'was released.';
END;
If the Sender of the event is not one of the buttons, we must determine which button to click. This is where the Tag property and the Components array property come in. As you noticed in Figure 3, SpeedButton1 had a Tag value of 1. . MainItem1 and PopupItem1 also have Tag values of 1. Therefore, if any of the menu items are selected, it's a simple matter of viewing their Tag values and transferring the event to the SpeedButton with the same Tag This is handled in the SpeedButtonClick handler:
For A: = 0 to ComponentCount-1 DO
IF Components [A] Is TspeedButton Then
With Components [A] as TspeedButton Do
if Tag = TComponent (Sender) .Tag thenThis code snippet scans the Components array and examines each component it finds. When a TSpeedButton is found, the code compares this object's Tag value with the Tag value of the object that originally fired the message. If the values are the same, then the code found the button that ultimately receives the event. Since the code has already determined that it's a TSpeedButton, this object's up / down state can now be toggled. Then, either the PushButton or ReleaseButton procedure is called With the selected speedbutton passed as the parameter as Follows:
Begin
Down: = NOT DOWN;
IF down kil
Pushbutton (Self.components [A])
Else
ReleaseButton (Self.components [A]);
END;
This Statement:
Pushbutton (Self.components [A])
Calls The Procedure Pushbutton, Passing Along The Parameter:
Self.components [a]
The PushButton procedure interprets this Self statement as the original Sender. The Self portion is required because we want to look at the Components property of Form1. Since the code uses a with statement to simplify readability, we must ensure that the code is viewing the correct Components Property. In this case, spetedButtons Also Have a Components Property and with welnout.
The PushButton procedure is where the timesheet database would be updated or other functions would be performed. Since the previous procedure handled the bulk of the work, PushButton simply performs the actions necessary when the button has been pressed. Remember that SpeedButtonClick did not send the actual Sender parameter, but sent a modified one that points to the SpeedButton regardless of how the button was selected. SpeedButtonClick's other procedure call, ReleaseButton, is likewise called to handle whatever events should occur when the button is released.Conclusion
Alone, the Sender parameter is a simple return address, allowing functions to trace which component triggered their event. But used in conjunction with a few other properties, such as Tag and Components, Sender becomes a powerful tool for tracing and filtering program flow. This ability to work around program limitations allows developers to create single, modular event handlers for components of all types, without the need for multiple if..then statements. This, of course, is just one way of extending Sender's abilities. There are as many Possibilities as there is it.