简体   繁体   中英

Problem with OnClick event signature in C++Builder

I would like to create a function which replaces the current image with another one. The problem is that I have 64 pictures to replace. I created a function with a TImage* Sender parameter but it works only when I set Sender as TObject* instead.

How can I change this function:

void __fastcall TForm1::Image1Click(TObject *Sender)
{
    Sender->Picture->LoadFromFile("puste.bmp");
}

into this

void __fastcall TForm1::Image1Click(TImage *Sender)
{
    Sender->Picture->LoadFromFile("puste.bmp");
}

I am using the VCL library.

You can't change the signature of the event handler. It has to be what the VCL expects it to be, which in this case is defined by the TNotifyEvent type, which is what the OnClick event is declared as:

typedef void __fastcall (__closure *TNotifyEvent)(System::TObject* Sender);

__property System::Classes::TNotifyEvent OnClick = {read=FOnClick, write=FOnClick, stored=IsOnClickStored};

However, you don't need to change the signature. All VCL components derive from TObject , and the Sender parameter points to the control that was clicked on. So, in this case, you can simply use a type-cast to access functionality that is specific to TImage , eg:

void __fastcall TForm1::Image1Click(TObject *Sender)
{
    static_cast<TImage*>(Sender)->Picture->LoadFromFile("puste.bmp");
}

You can then assign this 1 handler to all 64 of your TImage controls.

If you need to differentiate between different TImage controls, you can use the TImage 's Name or Tag property for that purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM