GUIアプリケーション

GUI アプリケーション (C# によるプログラミング入門)
http://ufcpp.net/study/csharp/lib_forms.html
概要、GUI部品、Form, GUI部品をFormに追加


System.Windows.Forms以下のForm, Menu, Buttonといったクラスを使う。
今はWPFがあるので、WPFを使うほうが便利かも。


最も単純なGUIアプリ

    Application.Run(new Form());  // デフォルトは300*300ドット
var f = new Form();
f.Width = 500;
f.Height = 300;
f.Text = "Sample Program";
Application.Run(f);

コンパイル時に/target:winexeを指定しないと、実行のたびにコンソールが表示されてしまう。


実際の複雑なGUIアプリを作る場合は、フォームごとにFormクラスの派生クラスを作る。

class Form1 : Form
{
  public Form1()
  {
    this.Width = 500;
    this.Height = 300;
    this.Text = "Sample Program";
  }
}


そして、ボタンなどの部品を作る。

Button button1 = new Button();
button1.Location = new Point(10, 10);
button1.Size = new Size(150,40);
button1.Text = "Click here";

これをフォームに追加するには、コンストラクタ内に書いて、フォームのControls.Addを呼び出す。

class Form1 : Form
{
  Button button1;

  public Form1()
  {
    this.Width = 500;
    this.Height = 300;
    this.Text = "Sample Program";

    this.button1 = new Button();
    this.button1.Location = new Point(10, 10);
    this.button1.Size = new Size(150, 40);
    this.button1.Text = "Click here";

    this.Controls.Add(this.button1);  // Controlsはこのフォームのコントロールの一覧を示すプロパティ
  }
}


つぎに、イベントハンドラを追加する。具体的には、

this.button1.Click += new EventHandler(this.Button1_Click); // イベントハンドラの追加

を上のソースに書き加えて、Button1_Click関数を別途定義する。


以上の全体像
http://ufcpp.net/study/csharp/fig/forms03.png


IDEを使えば、GUI上でボタンを追加したり出来るので便利。