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

徘徊边缘 提交于 2020-05-14 14:15:22

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/60329360/convert-the-sender-parameter-of-an-event-handler-in-order-to-read-the-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!