WisdomSoft - for your serial experiences.

ボタン

「押す」ことにによって何らかのアクションを実行するボタンコントロールについて紹介します。

ボタンの表示

ボタンは最も基本的なコントロールであり、ユーザーにとっても最も直感的な操作が可能な慣れ親しんだインターフェイスでしょう。ボタンはマウスのクリックなどによって「押す」ことによって、何らかのアクションが発生するコントロールです。

ボタンのような動作をするコントロールはいくつか存在し、ボタンに共通する基本機能は System.Windows.Forms.ButtonBase クラスで提供されています。このクラスは抽象クラスであり、全てのボタン関連コントロールは ButtonBase クラスから派生します。

System.Windows.Forms.ButtonBase クラス
System.Object
   System.MarshalByRefObject
      System.ComponentModel.Component
         System.Windows.Forms.Control
            System.Windows.Forms.ButtonBase
[ComVisibleAttribute(true)]
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)]
public abstract class ButtonBase : Control

コントロール設計者は、ボタンを作成する時はこのクラスを拡張するべきです。これによって、クラス利用者はボタンの概観や内部の機能とは関係なく、基本的なボタンの挙動を ButtonBase クラスのメンバを使って制御することができます。

もちろん Windows フォームのボタンも ButtonBase クラスを継承しています。最も一般的なボタンは System.Windows.Forms.Button クラスによるボタンコントロールです。

System.Windows.Forms.Button クラス
System.Object
   System.MarshalByRefObject
      System.ComponentModel.Component
         System.Windows.Forms.Control
            System.Windows.Forms.ButtonBase
               System.Windows.Forms.Button
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)]
[ComVisibleAttribute(true)]
public class Button : ButtonBase, IButtonControl

このクラスのコンストラクタはデフォルトコンストラクタのみです。

Button クラスのコンストラクタ
public Button()

ラベルと同様に、ボタンに表示する文字列は Text プロパティで設定します。

コード1
using System.Windows.Forms;
using System.Drawing;

class Test
{
	public static void Main(string[] args)
	{
		Button button = new Button();
		button.Bounds = new Rectangle(50, 20, 200, 100);
		button.Text = "Kitty on your lap";

		Form form = new Form();
		form.Controls.Add(button);

		Application.Run(form);
	}
}
実行結果
コード1 実行結果

コード1はフォームにボタンを追加しています。ボタンは 200 × 100 の大きさで、Text プロパティにボタン上に表示するテキストを設定しています。