「こんにちは」を表示したり、おみくじソフトを作ったりしましたが、なんとなくソフトっぽくない感じがしますよね?
Windowsらしく、ウインドウを使ったプログラムに変えてみましょう
public class TestApp
{
public static void Main()
{
System.Random rnd = new System.Random();
int n = rnd.Next(0, 4);
System.String m;
if (n == 1) {
m = "大吉";
} else if (n == 2) {
m = "小吉";
} else if (n == 3) {
m = "吉";
} else {
m = "凶";
}
System.Windows.Forms.Form f = new System.Windows.Forms.Form();
f.Width = 400;
f.Height = 300;
f.Font = new System.Drawing.Font("Arial", 20);
f.Text = "おみくじソフト";
System.Windows.Forms.Label a = new System.Windows.Forms.Label();
a.Width = 400;
a.Height = 100;
a.Text = "今日の運勢は " + m;
f.Controls.Add(a);
System.Windows.Forms.Application.Run(f);
}
}
実行結果
System.Windows.Forms.MessageBox を使っていたところが、System.Windows.Forms.Form(ウインドウ)とSystem.Windows.Forms.Label(文字表示部分)を使ったプログラムになりました。
これにボタンも追加して、クリックするたびに新しい結果が表示されるようにしてみます。
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 a;
private System.Windows.Forms.Button b;
public MainForm()
{
this.Width = 300;
this.Height = 200;
this.Text = "おみくじソフト";
a = new System.Windows.Forms.Label();
a.Width = 200;
a.Height = 50;
a.Top = 20;
a.Left = 20;
a.Text = "ボタンをクリックしてください";
a.Name = "a";
this.Controls.Add(a);
b = new System.Windows.Forms.Button();
b.Text = "おみくじをひく";
b.Top = 100;
b.Left = 20;
b.Click += b_Click;
this.Controls.Add(b);
}
private void b_Click(object btn, System.EventArgs e)
{
System.Random rnd = new System.Random();
int n = rnd.Next(0, 4);
System.String m;
if (n == 1)
{
m = "大吉";
}
else if (n == 2)
{
m = "小吉";
}
else if (n == 3)
{
m = "吉";
}
else
{
m = "凶";
}
a.Text = "今日の運勢は " + m;
}
}
実行結果