views:

174

answers:

1

Trying to write a simple VCL program for educating purposes (dynamicly created forms, controls etc). Have such a sample code:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    TForm* formQuiz = new TForm(this);
    formQuiz->BorderIcons = TBorderIcons() << biSystemMenu >> biMinimize >> biMaximize;
    formQuiz->Position = TPosition::poDesktopCenter;
    formQuiz->Width = 250;
    formQuiz->Height = 250;
    formQuiz->Visible = true;

    TButton* btnDecToBin = new TButton(formQuiz);
    btnDecToBin->Parent = formQuiz;
    btnDecToBin->Left = 88;
    btnDecToBin->Top = 28;
    btnDecToBin->Caption = "Dec to Bin";
    btnDecToBin->Visible = true;
}

I wonder how can i write a function for dynamic created button, so it would be called when the button is clicked. In this example i need a 'btnDecToBin->Click();' func but i don't know where should i place it.

Inside 'void __fastcall TForm1::Button1Click(TObject *Sender){}' ?

I will appreciate any input, some keywords for google too.

+3  A: 

You could do two things, you could either create an action and associate it with the button, or you could make a function like so:

void __fastcall TForm1::DynButtonClick(TObject *Sender)
{
    // Find out which button was pressed:
    TButton *btn = dynamic_cast<TButton *>(Sender);

    if (btn)
    {
        // Do action here with button (btn).
    }
}

You bind it to the button instance by setting the OnClick property btnDecToBin->OnClick = DynButtonClick please note that the function is inside the form Form1. This will work due to the nature of closures (compiler specific addition). The problem comes if you delete Form1 before formQuiz without removing the reference to the click event. In many ways it might be a more clean solution to use an Action in this case.

Edit: On other way to do this, if you have a standard layout for your quizforms, you could make a custom TQuizForm class inheriting from TForm. In this way you wouldn't have to bind the event each time you create the form.

TommyA
// Find out which button was pressed: TButton *btn = dynamic_cast<TButton *>(Sender);That won't tell you which button was pressed, it'll just be NULL if Sender is something /other than/ a TButton*
Liz Albin
Well in that case no button was pressed right? :) Besides if you add this function as the OnClick event for objects that are not buttons, I guess you would handle that in code. The line I mentioned does indeed tell you which object triggered the event, and in case of buttons it will tell you which button did so. The answer is as far as I can tell correct.
TommyA