Controls zur Laufzeit erstellen - C++ Builder Snippets
C++ Builder Snippets
Dynamisches ansteuern von Controls auf einer Form.
In diesem kleinen Beispiel möchte ich die Verwendung von zur Laufzeit erstellten Controls zeigen.
Es können mehrere Checkboxes erstellt werden. Aus dem Beispiel ist ebenfalls ersichtlich wie, das Click Event abgefragt oder zur Laufzeit geändert werden kann.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
//--------------------------------------------------------------------------- //******** ******** //******** Dieses Beispiel stammt von www.ecodes.de ******** //******** ******** #include <vcl.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; TCheckBox* MyTCheck; int Anzahl=0; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { GroupBox1->Enabled =true; MyTCheck=new TCheckBox(this); MyTCheck->Parent=this; MyTCheck->Caption="Meine CheckBox " + AnsiString(Anzahl); MyTCheck->Name="MC"+AnsiString(Anzahl); MyTCheck->Top=15 * Anzahl; MyTCheck->Left=20; MyTCheck->Width =180; MyTCheck->OnClick = ClickEvent; MyTCheck->Tag = Anzahl; Anzahl++; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button2Click(TObject *Sender) { //Zum Löschen alle Komponenten durchlaufen und überprüfen for(int CompC = 0; CompC < ComponentCount; CompC++) { if (Components[CompC]->Name.SubString(0,2) == "MC" && Components[CompC]->ClassNameIs("TCheckBox")) { delete Components[CompC]; CompC--; } } Anzahl=0; } //--------------------------------------------------------------------------- void __fastcall TForm1::ClickEvent(TObject *Sender){ int az= dynamic_cast<TCheckBox*>(Sender)->Tag; ShowMessage ("CheckBox " + AnsiString(az) +" geklickt"); } void __fastcall TForm1::Button3Click(TObject *Sender) { for(int CompC = 0; CompC < ComponentCount; CompC++) { if (Components[CompC]->Name.SubString(0,2) == "MC" && Components[CompC]->ClassNameIs("TCheckBox")) { //Event deaktivieren dynamic_cast<TCheckBox*>(Components[CompC])->OnClick=NULL; //Checked = true setzen dynamic_cast<TCheckBox*>(Components[CompC])->Checked=true; //Event wieder aktivieren dynamic_cast<TCheckBox*>(Components[CompC])->OnClick=ClickEvent; } } } //--------------------------------------------------------------------------- |