S_a_k_Uの日記みたいなDB

~サクゥーと呼ばないで~

WindowFormを動的に生成して実行する

プロジェクトが「WindowsFormアプリケーション」じゃない場合なんかに、テスト用のフォームを使ってテストしたい時に。
ちなみに、下記はクラスライブラリ内でも実行可能だけど、参照設定にSystem.Windows.Formsを追加してやる必要がある。

using System;

namespace ClassLibrary
{
    public class TestClass 
    {
        [STAThread]
        static void Main()
        {
            // フォーム(TestForm)を生成する
            System.Windows.Forms.Form f = new TestForm();
            // フォームを実行する
            f.ShowDialog();
            System.Diagnostics.Debug.WriteLine("終了しました。");
        }
    }
    // TestFormクラス
    public class TestForm : System.Windows.Forms.Form
    {
        // フォーム内に配置するボタン
        private System.Windows.Forms.Button Button1 = new System.Windows.Forms.Button();
        // フォーム内に配置するテキストボックス
        private System.Windows.Forms.TextBox TextBox1 = new System.Windows.Forms.TextBox();
        public TestForm()
        {
            // Windowタイトルを設定する
            this.Text = "Hellow world.";

            //ボタンのプロパティを設定する
            this.Button1.Text = "ポチっとな";
            //ボタンのサイズと位置を設定する
            this.Button1.Location = new System.Drawing.Point(10, 10);
            this.Button1.Size = new System.Drawing.Size(100, 20);
            //ボタンのクリックイベントにEventHandlerを設定する
            this.Button1.Click += new EventHandler(Button1_Click);
            //フォームに追加する
            this.Controls.Add(this.Button1);

            //テキストボックスのサイズと位置を設定する
            this.TextBox1.Location = new System.Drawing.Point(10, 40);
            this.TextBox1.Size = new System.Drawing.Size(240, 200);
            this.TextBox1.Multiline = true;
            this.TextBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            //フォームに追加する
            this.Controls.Add(this.TextBox1);


        }
        // Button1のクリックイベント処理
        private void Button1_Click(object sender, EventArgs e)
        {
            this.TextBox1.Text += DateTime.Now + "にポチっとされました";
            //System.Console.WriteLine(DateTime.Now +"にポチっとされました");
        }
    }
}