BCB動態生成(用程式碼生成)按鈕的方法
阿新 • • 發佈:2019-01-26
其實, 要生成某一個某一個, 完全可以採用控制其Visible屬性來實現, 生成的時候, 類似於讓其可見。 但是呢, 提前畫一個按鈕到介面, 容易干擾開發人員的編輯, 於是可以採用程式碼來生成:
.h檔案:
//--------------------------------------------------------------------------- #ifndef Unit1H #define Unit1H //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> //--------------------------------------------------------------------------- class TForm1 : public TForm { __published: // IDE-managed Components TButton *Button1; void __fastcall Button1Click(TObject *Sender); private: // User declarations public: // User declarations __fastcall TForm1(TComponent* Owner); void __fastcall TForm1::fun(TObject *Sender); }; //--------------------------------------------------------------------------- extern PACKAGE TForm1 *Form1; //--------------------------------------------------------------------------- #endif
.cpp檔案:
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { TButton *my = new TButton(Form1); my->Parent = Form1; // 不可少 my->Top = 100; my->Left = 100; my->Height = 125; my->Width = 175; my->Caption = "Button2"; my->OnClick = fun; } //--------------------------------------------------------------------------- void __fastcall TForm1::fun(TObject *Sender) { ShowMessage("Button2 clicked"); }