C++ Builder、TShapes、如何更改颜色 OnMouseEnter

标签 c++ c++builder onmouseover c++builder-xe7

嘿!我正在尝试以编程方式创建 TShape。当我运行程序并单击按钮时 - 一切正常。但是当我再次单击该按钮时,事件 OnMouseEnter(OnMouseLeave) 仅适用于最后一个形状。不适用于之前的任何一个。

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

最佳答案

您的 OnMouse... 事件处理程序使用 i 索引到 Shape[] 数组,但是 i 包含您创建的 last TShape 的索引(顺便说一句,您没有填充 Shape[0]m,因为您递增 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;
}

关于C++ Builder、TShapes、如何更改颜色 OnMouseEnter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29368312/

相关文章:

c++ - 如何检查 UnicodeString 的字符?

c++ - 在 C++ Builder 类中定义默认函数参数和参数太少错误

jquery - Onmouseover 恢复为原始文本

c++ - 预定义宏的 __FILE__、__LINE__、__func__、stringify(#) 是如何工作的?

c++ - 正在打印指向定义的 int 的成员指针

c++builder - 如何在 Borland Builder XE 中同时显示头文件和源文件?

jquery - jquery中鼠标悬停时获取元素的id

javascript - 在转发器控件中设置子标记属性

c++ - 这个 makefile 有什么问题

c++ - 错误 : no match for 'operator>>' in 'std::cin >> stopat'