C ++ Builder — C ++ Builder, TShapes, Как изменить цвет OnMouseEnter

Хей! Я пытаюсь программно создать TShape. Когда я запускаю программу и нажимаю кнопку — все работает. Но когда я снова нажимаю кнопку, событие OnMouseEnter (OnMouseLeave) работает только с LAST Shape. Не работает ни с одним из предыдущих.

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

0

Решение

Ваш OnMouse... обработчики событий используют i индексировать в Shape[] массив, но i содержит индекс прошлой TShape вы создали (и кстати, вы не заполняете Shape[0]м, как вы увеличиваете i перед созданием первого TShape).

Чтобы сделать то, что вы пытаетесь, обработчики событий должны использовать свои Sender параметр, чтобы знать, какой TShape является В настоящее время запуск каждого события, например:

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

Другие решения