2015-06-19 22 views
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 ... 
}