Search code examples
c++buildervcl

C++: How do I make a VCL component reference itself?


I'm using C++ Builder in RAD Studio 10.2. I'm not sure if I asked this correctly in the title, but what I'm trying to say is that whenever I use the C++ keyword 'this', it references the Parent of the component that I'm trying to access, but not the component itself.

For example, the code below changes the Form's color and font color instead of the Panel's color and font color:

void __fastcall TForm1::Panel1MouseEnter(TObject *Sender)
{
    this->Color = cl3DLight;
    this->Font->Color = clMaroon;
}

Also, if I do the same as above but omit the keyword 'this', it still changes the Form's properties instead of the Panel's (see code below).

void __fastcall TForm1::Panel1MouseEnter(TObject *Sender)
{
    Color = cl3DLight;
    Font->Color = clMaroon;
}

How would I code this so it accesses the Panel's 'Color' and 'Font->Color' instead of the Form's? Thank you.

Note: The reason that I haven't just done it as: Panel1->Color = "cl3DLight"; is because I'm trying to find a way to do it for components created at run-time.


Solution

  • The Sender parameter represents the component that is generating the event. You can typecast that pointer to the proper type in order to access that component's properties.

    If you know for sure that everything attached to the event is a TPanel, you can typecast it directly (as Remy pointed out in comments below):

    void __fastcall TForm1::Panel1MouseEnter(TObject *Sender)
    {
        TPanel *panel = static_cast<TPanel *>(Sender);
        panel->Color = cl3DLight;
        panel->Font->Color = clMaroon;
    }
    

    If you're using the same event handler for different control types, you can test for the appropriate type instead:

    void __fastcall TForm1::Panel1MouseEnter(TObject *Sender)
    {
        TPanel *panel = dynamic_cast<TPanel *>(Sender);
        if (panel) 
        {
          panel->Color = cl3DLight;
          panel->Font->Color = clMaroon;
        }
    }