[Tips][Label] テキストの配置を取得・設定する

スポンサーリンク

本記事はWindowsアプリケーションのTipsです。


Labelコントロールのテキストの配置を取得・設定するには、TextAlignプロパティを使用します。

下記はTextAlignプロパティを使用する例です。

VBの例

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'テキストの表示位置をコントロール内の中段右端にする
    Label1.TextAlign = ContentAlignment.MiddleRight
    'テキストを表示
    Label1.Text = "テキストを表示"
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim strAlignment As String

    'テキストの配置を確認する
    Select Case Label1.TextAlign
        Case ContentAlignment.TopLeft
            strAlignment = "上段左端"
        Case ContentAlignment.TopCenter
            strAlignment = "上段中央"
        Case ContentAlignment.TopLeft
            strAlignment = "上段右端"
        Case ContentAlignment.MiddleLeft
            strAlignment = "中段左端"
        Case ContentAlignment.MiddleCenter
            strAlignment = "中段中央"
        Case ContentAlignment.MiddleRight
            strAlignment = "中段右端"
        Case ContentAlignment.BottomLeft
            strAlignment = "下段左端"
        Case ContentAlignment.BottomCenter
            strAlignment = "下段中央"
        Case ContentAlignment.BottomRight
            strAlignment = "下段右端"
        Case Else
            strAlignment = ""
    End Select

    MessageBox.Show("現在テキストは「" & strAlignment & "」に配置されています。")
End Sub

C#の例

private void Form1_Load(object sender, EventArgs e)
{
    // テキストの表示位置をコントロール内の中段右端にする
    label1.TextAlign = ContentAlignment.MiddleRight;
    // テキストを表示
    label1.Text = "テキストを表示";
}
 
private void button1_Click(object sender, EventArgs e)
{
    string strAlignment = "";

    // テキストの配置を確認する
    switch (label1.TextAlign)
    {
        case ContentAlignment.TopLeft:
            strAlignment = "上段左端";
            break;
        case ContentAlignment.TopCenter:
            strAlignment = "上段中央";
            break;
        case ContentAlignment.TopRight:
            strAlignment = "上段右端";
            break;
        case ContentAlignment.MiddleLeft:
            strAlignment = "中段左端";
            break;
        case ContentAlignment.MiddleCenter:
            strAlignment = "中段中央";
            break;
        case ContentAlignment.MiddleRight:
            strAlignment = "中段右端";
            break;
        case ContentAlignment.BottomLeft:
            strAlignment = "下段左端";
            break;
        case ContentAlignment.BottomCenter:
            strAlignment = "下段中央";
            break;
        case ContentAlignment.BottomRight:
            strAlignment = "下段右端";
            break;
    }

    MessageBox.Show("現在テキストは「" + strAlignment + "」に配置されています。");
}
Please follow and like us:

コメント

タイトルとURLをコピーしました