Programming VB/VB.NET How to Use the "Sender" Parameter to Share Events--Sender and Share Events Examples in C++Builder

How to use the "Sender" parameter in C++Builder program.

In an event handler, the Sender parameter indicates which component received the event and therefore called the handler. Sometimes it is useful to have several components share an event handler that behaves differently depending on which component calls it. You can do this by using the Sender parameter.

See an example, create a new project, and put two buttons on the form. Change button1's caption to "Hello" and button2's caption to "My boy". Then double click the button1, assign the following codes on its handler.

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    TButton* pButton = (TButton*)Sender;

    ShowMessage(pButton->Name);
    ShowMessage(pButton->Caption);
    ShowMessage(pButton->ClassName());
    ShowMessage(pButton->Parent->Name);
}
//---------------------------------------------------------------------------

Run the project, click button1 see what happen. Then close the application, select button2 on the form, choose the Events tab in the Object Inspector, from the dropdown list right to the "OnClick" item, select "Button1Click" to be its handle event.

Run the program again. Click button1, and click button2, see is there any different messages showed by them. So, when you have a procedure which could be share by many components, you could use this method to write it, then use the "Sender" parameter to do some difference between them. Of course, you could make a lot of components to share one event. See following.

Displaying and coding shared events

When components share events, you can display their shared events in the Object Inspector. First, select the components by holding down the Shift key and clicking on them in the Form Designer; then choose the Events tab in the Object Inspector. From the Value column in the Object Inspector, you can now create a new event handler for, or assign an existing event handler to, any of the shared events.


Add comment


Security code
Refresh

Programming - VB/VB.NET