如何在 C# 中设置居中显示
在 C# 中,可以通过多种方式设置控件的文本居中显示:
1.使用 StringAlignment 枚举
<code class="csharp">label1.TextAlign = StringAlignment.Center;</code>
2.使用 TextFormatFlags 枚举
<code class="csharp">label1.TextFormatFlags = TextFormatFlags.HorizontalCenter;</code>
3.使用 Padding 属性
<code class="csharp">label1.Padding = new Padding(10, 0, 10, 0);</code>
4.使用 indent 属性
<code class="csharp">label1.Indent = (label1.Width - label1.Text.Length) / 2;</code>
示例代码:
<code class="csharp">using System.Drawing;
using System.Windows.Forms;
public class Form1 : Form
{
public Form1()
{
Label label1 = new Label();
label1.Text = "居中显示文本";
// 使用 StringAlignment 枚举设置居中显示
label1.TextAlign = StringAlignment.Center;
// 设置控件大小和位置
label1.Size = new Size(200, 50);
label1.Location = new Point(100, 100);
this.Controls.Add(label1);
}
}</code> 