在运行时向组件添加事件

时间:2015-06-19 01:14:34

标签: c++builder

您知道如何在运行时向构造的按钮添加事件吗? 我理解如何在运行时构建组件,但添加事件是另一回事。有任何例子来解释它是如何工作的吗?

由于

1 个答案:

答案 0 :(得分:0)

VCL事件只是指向特定对象的类方法的指针。您可以直接指定该指针,例如:

__fastcall TForm1::TForm1(TComponent *Owner)
    : TForm(Owner)
{
    TButton *btn = new TButton(this);
    btn->Parent = this;
    // set other properties as needed...

    btn->OnClick = &ButtonClicked;
    /*
    behind the scenes, this is actually doing the equivalent of this:

    TMethod m;
    m.Data = this; // the value of the method's hidden 'this' parameter
    m.Code = &TForm1::ButtonClicked; // the address of the method itself
    btn->OnClick = reinterpret_cast<TNotifyEvent&>(m);
    */
}

void __fastcall TForm1::ButtonClicked(TObject *Sender)
{
    // do something ...
}
相关问题