直接 TextBox と Button を貼り付ける

ツールボックスから張り付ける方法は、初心者には解り易いかも知れませんが、慣れてくると煩わしく感じます。
そこでツールボックスを使わないで、直接 Form に TextBox と Button を貼り付けます。
こちらの方が手間もかからず、スマートなプログラムを作成することが出来ます。

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

プロジェクトの設定

  1. 空のプロジェクトを作成して、次のファイルを格納して下さい。
    プログラムをプロジェクトに取り込んで下さい。
    詳細は Form を作成する を参照して下さい。
    ファイル名 説明
    TextButton.cs 直接ボタンを貼り付ける
  2. ソースコード(TextButton.cs)です。
    /*************************************************************/
    /*★ ボタンのクリックで TEXT を取得して表示する    前田 稔 ★*/
    /*************************************************************/
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    public class MyForm : Form
    {
        private Button button1;
        private TextBox textBox1;
        private string str = "C#";
    
        public MyForm()
        {
            // textBox1
            textBox1 = new TextBox();
            textBox1.Parent = this;
            textBox1.Location = new System.Drawing.Point(83, 205);
            textBox1.Name = "textBox1";
            textBox1.Size = new System.Drawing.Size(100, 19);
            //this.textBox1.TabIndex = 0;
        
            // button1
            button1 = new Button();
            button1.Parent = this;
            button1.Location = new Point(94, 231);
            button1.Text = "押す";
            button1.BackColor = SystemColors.Control;
            button1.Click += new System.EventHandler(this.button1_Click);
    
            Paint += new PaintEventHandler(MyHandler);
        }
    
        private void MyHandler(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Font f = new Font("MS 明朝", 40);
            g.DrawString(str, f, Brushes.Blue, new PointF(10F, 80F));
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            str = textBox1.Text;
            Invalidate();
            MessageBox.Show(str,"Button Click");
        }
    }
    
    class form01
    {
        public static void Main()
        {
            MyForm mf = new MyForm();
            Application.Run(mf);
        }
    }
    

【演習】

TextBox にメッセージを入力して Button をクリックするとウインドウに表示されることを確かめて下さい。
実質的に TextBox と Button を貼り付ける と同じプログラムなので見比べて下さい。
このプロジェクトでは form.resx ファイルは使用しません。

超初心者のプログラム入門(C# Frame Work)