How can I centralize the event handling for related controls?

How can I centralize the event handling for related controls?

I’m a VB programmer who is new to Delphi. How do I centralize event handling for related controls?

In VB, there is a concept of control arrays in which each control in the array is of the same type and has an index (subscript)that uniquely identifies it. This index is then passed as aparameter to all event subroutines that the particular controlsupports.

For example, below is an example of a three-control arrayevent subroutine for three buttons:

     Private Sub Btn_Click(Index As Integer)        Select Case Index            Case 0            { Button 0 clicked }                    MsgBox ("Yes")            Case 1            { Button 1 clicked }                    MsgBox ("No")            Case 2            { Button 2 clicked }                    MsgBox ("Maybe")        End Select     End Sub

Is there an equivalent in Delphi?

Yes, there is an equivalent. In fact, Delphi’s approach takes it astep further by allowing you to centralize events for differentcontrol types, as long as they can receive the same event.

Delphi does not have the concept of a control array, but instead hasmore logical implementation. Event handlers, as they are called inDelphi, are callback functions that are not tied to anyparticular control, but are assigned to a control’s eventproperty value.

What is a control event property value?

The Object Inspector, which is similar to the Properties window in VB,has two tabs: a Properties tab that looks and operates like theProperties window in VB, and the Events tab, which has all the events aparticular control supports. Adjacent to each event is a combo boxthat stores the event property value. This is where you can manuallyadd the name of an event handler or select from the drop-down list ofalready existing event handlers.

Think of the Events tab as a listof open jacks that you plug into if you are interested in performinga customized reaction to a specific event. In technicalterms, these open jacks can potentially store the address of an eventhandler/callback function that will be called if that particularcontrol experiences that event.

Below is an example of a Delphi event handler. What makes it share-ablefrom the end-user perspective is the Sender parameter, which is oftype TObject. All classes in Delphi are ultimately derived fromTObject; therefore, you can always test for the specific object/controlfor which the event was generated.

procedure TForm1.Clicked(Sender: TObject);begin     if Sender = Label1 then        ShowMessage ('Label clicked');     if Sender = Button1 then        ShowMessage ('Button clicked');     if Sender = Edit1 then        ShowMessage ('Edit clicked');end;


Share the Post: