c++c++builderonmouseoverc++builder-xe7

C++ Builder, TShapes, How to change color OnMouseEnter


Hej! I'm trying to programmatically create a TShape. When I run the program and click the button - everything works. But when I click the button again, the event OnMouseEnter(OnMouseLeave) works only with the LAST Shape. Does not work with any of the previous.

    int i=0;
    TShape* Shape[50];
    void __fastcall TForm1::Button1Click(TObject *Sender)
{
    int aHeight = rand() % 101 + 90;
    int bWidth = rand() % 101 + 50;
    i++;
    Shape[i] = new TShape(Form1);
    Shape[i]->Parent = this;
    Shape[i]->Visible = true;
    Shape[i]->Brush->Style=stCircle;
    Shape[i]->Brush->Color=clBlack;

    Shape[i]->Top =    aHeight;
    Shape[i]->Left = bWidth;
    Shape[i]->Height=aHeight;
    Shape[i]->Width=bWidth;

    Shape[i]->OnMouseEnter = MouseEnter;
    Shape[i]->OnMouseLeave = MouseLeave;

    Label2->Caption=i;


    void __fastcall TForm1::MouseEnter(TObject *Sender)
{
    Shape[i]->Pen->Color = clBlue;
     Shape[i]->Brush->Style=stSquare;
     Shape[i]->Brush->Color=clRed;
}



void __fastcall TForm1::MouseLeave(TObject *Sender)
{
    Shape[i]->Pen->Color = clBlack;
    Shape[i]->Brush->Style=stCircle;
    Shape[i]->Brush->Color=clBlack;
}

Solution

  • Your OnMouse... event handlers are using i to index into the Shape[] array, but i contains the index of the last TShape you created (and BTW, you are not populating Shape[0]m as you are incrementing i before creating the first TShape).

    To do what you are attempting, the event handlers need to use their Sender parameter to know which TShape is currently triggering each event, eg:

    TShape* Shape[50];
    int i = 0;
    
    void __fastcall TForm1::Button1Click(TObject *Sender)
    {
        ...
    
        Shape[i] = new TShape(this);
        Shape[i]->Parent = this;
        ...
        Shape[i]->OnMouseEnter = MouseEnter;
        Shape[i]->OnMouseLeave = MouseLeave;
    
        ++i;
        Label2->Caption = i;
    }
    
    void __fastcall TForm1::MouseEnter(TObject *Sender)
    {
        TShape *pShape = static_cast<TShape*>(Sender);
    
        pShape->Pen->Color = clBlue;
        pShape->Brush->Style = stSquare;
        pShape->Brush->Color = clRed;
    }
    
    void __fastcall TForm1::MouseLeave(TObject *Sender)
    {
        TShape *pShape = static_cast<TShape*>(Sender);
    
        pShape->Pen->Color = clBlack;
        pShape->Brush->Style = stCircle;
        pShape->Brush->Color = clBlack;
    }