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.
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:
You bind it to the button instance by setting the OnClick property
btnDecToBin->OnClick = DynButtonClickplease 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 deleteForm1beforeformQuizwithout 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
TQuizFormclass inheriting fromTForm. In this way you wouldn’t have to bind the event each time you create the form.