c++buildervclc++builder-6

Convert the Sender parameter of an event handler in order to read the control's Name?


I am writing a Form application using Borland C++Builder 6.0. I have put 2 TImage controls and I have generated the OnClick event handler as shown below:

void __fastcall TForm1::Image1Click(TObject *Sender)
{
   AnsiString imageName;

   TImage *image;

   // How can I get the image name via the *Sender ?
   // How can I convert *Sender into TImage
   image = (TComponent)*Sender;

   imageName = image->Name;
}

I have assigned the same OnClick event on both of my TImage controls.

What I want to achieve is to have one event handler that reads the Name of the TImage which is clicked.

As far as I know, this can be done through the TObject *Sender parameter, but I cannot understand how I can convert the Sender into a TImage.


Solution

  • You are on the right track that a simple type-cast will suffice, but your syntax is wrong. Try this instead:

    void __fastcall TForm1::Image1Click(TObject *Sender)
    {
       TImage *image = (TImage*)Sender;
       // alternatively:
       // TImage *image = static_cast<TImage*>(Sender);
    
       AnsiString imageName = image->Name;
    }