メモ帳でできるプログラミング C#

(サンプル)足し算計算機

入力欄を2つ持ち、ボタンを押すと2つの入力値を足すだけの簡単なフォームを作成します。

入力制限や入力チェックはおおざっぱです。

実行結果

プログラム

public class TestApp
{
	public static void Main()
	{
		System.Windows.Forms.Application.Run(new MainForm());
	}
}

public class MainForm : System.Windows.Forms.Form
{
	private System.Windows.Forms.Label c1;
	private System.Windows.Forms.TextBox c2;
	private System.Windows.Forms.Label c3;
	private System.Windows.Forms.TextBox c4;
	private System.Windows.Forms.Label c5;
	private System.Windows.Forms.Label c6;
	private System.Windows.Forms.Button c7;

	public MainForm()
	{
		this.Width = 300;
		this.Height = 150;
		this.Text = "足し算計算機";

		c1 = new System.Windows.Forms.Label();
		c1.Top = 10;
		c1.Left = 10;
		c1.AutoSize = true;
		c1.Text = "数字を2つを入力してください";
		this.Controls.Add(c1);

		c2 = new System.Windows.Forms.TextBox();
		c2.Top = 40;
		c2.Left = 10;
		c2.Width = 50;
		this.Controls.Add(c2);

		c3 = new System.Windows.Forms.Label();
		c3.Top = 40;
		c3.Left = 70;
		c3.Width = 20;
		c3.Text = "+";
		this.Controls.Add(c3);

		c4 = new System.Windows.Forms.TextBox();
		c4.Top = 40;
		c4.Left = 90;
		c4.Width = 50;
		this.Controls.Add(c4);

		c5 = new System.Windows.Forms.Label();
		c5.Top = 40;
		c5.Left = 150;
		c5.Width = 20;
		c5.Text = "=";
		this.Controls.Add(c5);

		c6 = new System.Windows.Forms.Label();
		c6.Top = 40;
		c6.Left = 170;
		c6.Width = 100;
		this.Controls.Add(c6);

		c7 = new System.Windows.Forms.Button();
		c7.Text = "計算する";
		c7.Top = 70;
		c7.Left = 10;
		c7.Click += c7_Click;
		this.Controls.Add(c7);
	}

	private void c7_Click(object btn, System.EventArgs e)
	{
		try
		{
			c6.Text = (double.Parse(c2.Text) + double.Parse(c4.Text)).ToString();
		}
		catch
		{
			c6.Text = "計算できません";
		}
	}
}