C# - 将“System.Drawing.Size”元素转换为整数

本文关键字:元素 转换 整数 Size Drawing System | 更新日期: 2023-09-27 18:36:00

我正在使用Visual C#中的.NET表单。我动态创建了一个标签,单击按钮时会显示该标签。这一切都工作正常;我试图做的是定位它,使元素位于表单的中心。通常,我只是将其设置为窗体大小的一半,减去元素大小的一半,但这当然不起作用,因为我也以编程方式设置文本。

我的标签代码如下:

if(part == 1){
        theLabel.Text = "Choose a name for your character!";
}
theLabel.ForeColor = Color.DarkGray;
theLabel.Font = new Font("Arial", 14, FontStyle.Bold);
theLabel.Location = new Point();

我在这里尝试了很多东西,但我想不出办法。我已经尝试了int[] sizes = (int)theLabel.Size和其他各种方法,但我就是无法让它工作。有没有另一种方法可以将此元素排列到中间?

C# - 将“System.Drawing.Size”元素转换为整数

如果我是你,我会这样做。

Label theLabel;
private void button1_Click(object sender, EventArgs e)
        {
            theLabel = new Label();
            theLabel.AutoSize = true;
            theLabel.BackColor = Color.Red;
            theLabel.TextAlign = ContentAlignment.MiddleCenter;
            theLabel.Text = "Choose a name for your character!";
            this.Controls.Add(this.theLabel);
            theLabel.Left = (this.ClientRectangle.Width - theLabel.Width) / 2;
            //theLabel.ForeColor = Color.Black;
            theLabel.Top = 25;
            theLabel.Show();
        }