ボタンについて

この章ではボタンについて解説します。

.NET Frameworkにおいてボタンを表すクラスはButtonです。
下記はボタンを使ったサンプルコードです。

using System;
using System.Drawing;
using System.Windows.Forms;

public class Sample
{
    public static void Main(String[] args)
    {
        Form f = new Form();
        Button button = new Button();
        button.Location = new Point(10, 10);
        button.Text = "ボタン";
        button.Click += new EventHandler(Button1_Click);
        f.Controls.Add(button);
        Application.Run(f);
    }
    
    public static void Button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("ボタンを押した");
    }
}

サンプルを実行するとウィンドウが表示され、その中にボタンが表示されます。
ボタンを押下すると、メッセージボックスが表示されます。

このようにボタンを押すなどのなんらかアクションによって、処理が行われることをイベント駆動と言います。

button.Click += new EventHandler(Button1_Click);

上記のコードによってボタンをクリックした時に行う処理を追加しています。

Buttonクラスの主なプロパティ

表示文字列

ボタンに表示する文字列を設定するにはTextプロパティを使用します。

表示位置

ボタンの位置を設定するにはLocationプロパティを設定します。
Locationプロパティの型はPointクラスになります。



inserted by FC2 system