![]() |
![]() |
|||||
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
|
Q: Get information from TObject* Sender in an eventAnswer:The event handlers in BCB pass a TObject pointer called Sender to the handler function. This pointer tells the handler function what VCL control generated the event. However, since the pointer is a TObject pointer, you cannot treat it as if it were a button or a menu item. To obtain useful information from the Sender argument, you will often times need to cast the pointer. The code below uses the new dynamic_cast C++ type safe cast to convert Sender to a concrete VCL object. void __fastcall TForm1::Button2Click(TObject *Sender) { TButton *btn = dynamic_cast< TButton * >(Sender); if(!btn) return; btn->Caption = "New Caption"; } dynamic_cast returns NULL if the Sender object is not a valid instance of the class. In the code above, dynamic_cast returns NULL if Sender is not really a button. The if test checks to see if the cast operation failed. Note:Sometimes, you can live without the cast if you only need to identify who triggered the event. The code below clarifies what I mean. void __fastcall TForm1::Button2Click(TObject *Sender) { // Test Sender to see if its the same pointer as Button1. // If they are the same, change the Caption of Button1 if(Button1 == Sender) Button1->Caption = "New Caption"; } | ||||||
All rights reserved. |