WisdomSoft - for your serial experiences.

ラベル

標準ラベルは設定された文字列をテキストとして描画する単純な機能だけを提供します。

テキストを表示する

フォーム上にテキストを表示するには System.Windows.Forms.Label クラスを用いる方法が最も簡単です。Label クラスは Control クラスを継承するコントロールの一種で、Text プロパティに設定されている文字列をテキストとして画面に表示するラベルを表します。

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

Label クラスのコンストラクタはパラメータを受け取りません。

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

Label クラスのオブジェクトを作成し、フォームに子コントロールとして追加すると、Text プロパティに設定されている文字列が画面に表示されます。

コード1
using System.Windows.Forms;

class Test
{
	public static void Main(string[] args)
	{
		Label label = new Label();
		label.Dock = DockStyle.Fill;
		label.Text = "Kitty on your lap";

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

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

コード1は単純に Label クラスのオブジェクトを作成し、Text プロパティに文字列を設定してフォームに追加しています。ラベルは、既定でコントロールの左上隅にテキストを描画します。

前述した ForeColor による前景色の変更を用いることで、表示するテキストの色を変更できます。

テキストのフォントやサイズを変更するには Font プロパティからフォントを設定します。

Label クラス Font プロパティ
public virtual Font Font { get; set; }

このプロパティは System.Drawing.Font クラスのオブジェクトでテキストの描画に用いるフォントを表します。 

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

class Test
{
	public static void Main(string[] args)
	{
		Label label = new Label();
		label.Dock = DockStyle.Fill;
		label.Text = "Kitty on your lap";
		label.ForeColor = Color.Red;
		label.Font = new Font("Times New Roman", 32);

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

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

コード2はラベルが表示するテキストの色とサイズを変更しています。このように、コントロールが表示するテキストの色やフォントは、ラベルに限らずすべてのコントロールに共通して基本クラスである Control クラスのプロパティで設定できます。