CLI で Button を貼り付ける

Button を貼り付けるプログラムを CLI で作成します。

前田稔(Maeda Minoru)の超初心者のプログラム入門

プログラムの説明

  1. ソースプログラムです。
    ファイル名 説明
    CliButton.cpp Button を貼り付ける
  2. ウインドウに Button を貼り付けるプログラムを CLI で作成します。
    GUI で作成した ToolBox から TextBox と Button を貼り付ける と比べてみて下さい。
    今回も必要なのは、ごく簡単なプログラムファイル一本だけです。
    コンパイルと実行の方法は Set UP を参照して下さい。
  3. #using と using namespace の宣言です。
    Button を貼り付けるときは System::Drawing; が必要です。
        #using <System.dll>
        #using <System.Windows.Forms.dll>
        #using <System.Drawing.dll>
    
        using namespace System;
        using namespace System::Windows::Forms;
        using namespace System::Drawing;
        
  4. private: で Button^ を宣言します。
    ^ はポインタを表す記号です。
    public: で宣言しても差し支え無いのですが、Class 内だけで使われる領域は private: で宣言しましょう。
        System::Windows::Forms::Button^  button1;
        
  5. Constructor で Button を生成して、Form に貼り付けます。
    gcnew System::Windows::Forms::Button() で Button を生成します。
    Button の座標やサイズを変更してみて下さい。
    Click += でボタンがクリックされたときのイベントメソッドを設定します。
        FormClass()
        {
            // button1
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->button1->Location = System::Drawing::Point(47, 80);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(75, 23);
            this->button1->Text = L"button1";
            this->button1->Click += gcnew System::EventHandler(this, &FormClass::Button_Click);
        
  6. Button の生成が終われば Form に貼り付けます。
    Controls->Add(this->button1) が Button を貼り付けるコードです。
            // Form
            this->Controls->Add(this->button1);
            this->Text = L"Button Click";
        
  7. ボタンがクリックされたときのイベントメソッドでは、MessageBox を表示してみました。
        private: System::Void Button_Click(System::Object^  sender, System::EventArgs^  e)
        {
            MessageBox::Show("Button がクリックされました","caption");
        }
        

【演習】

ToolBox から TextBox と Button を貼り付ける に習って、クリックされた回数を TextBox に表示して下さい。

超初心者のプログラム入門(C/C++)