在C#中以编程方式添加标签

时间:2016-05-23 18:01:53

标签: c# winforms

我正在尝试使用标签来创建一个标签,这个标签必须以编程方式完成一个砖块破坏者游戏,我的目标是这样,无论我使用的屏幕尺寸不同的台式电脑,拍板总是在屏幕的底部中心但由于某种原因没有显示桨(标签)。这是我正在使用的代码:

Screen userScreen = Screen.PrimaryScreen;
int screenWidth = userScreen.WorkingArea.Width;
int screenHeight = userScreen.WorkingArea.Height;

this.Width = screenWidth;
this.Height = screenHeight;

Label lblPaddle = new Label();
lblPaddle.BackColor = Color.White;          
lblPaddle.BorderStyle = BorderStyle.FixedSingle;
//lblPaddle.Left = (this.ClientSize.Width - lblPaddle.Width) / 2;
//lblPaddle.Top = (this.ClientSize.Height - lblPaddle.Height) / 2;
//lblPaddle.Size = this.ClientSize;
int lblPaddleWidth = (int)(screenWidth * 0.15);
int lblPaddleHeight = lblPaddle.Height;
int lblPaddleXCoord = (screenWidth / 2) - (lblPaddleWidth / 2);
int lblPaddleYCoord = screenHeight - lblPaddleHeight - (int)(screenHeight * 0.1);
lblPaddle.SetBounds(lblPaddleXCoord, lblPaddleYCoord, lblPaddleWidth, lblPaddleHeight);

this.Controls.Add(lblPaddle);

有评论的部分是我试图使其发挥作用的不同方法。 为什么没有显示?

2 个答案:

答案 0 :(得分:0)

在这样调用时,我的代码完全没有问题:

   public partial class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
         InitLabel();
      }

      private void InitLabel()
      {
         Screen userScreen = Screen.PrimaryScreen;
         int screenWidth = userScreen.WorkingArea.Width;
         int screenHeight = userScreen.WorkingArea.Height;

         this.Width = screenWidth;
         this.Height = screenHeight;

         // I added the following 2 lines because the form was below the task bar
         this.StartPosition = FormStartPosition.Manual;
         this.Location = new Point(0,0);

         Label lblPaddle = new Label();
         lblPaddle.Name = "lblPaddle";
         lblPaddle.BackColor = Color.White;
         lblPaddle.BorderStyle = BorderStyle.FixedSingle;
         int lblPaddleWidth = (int)(screenWidth * 0.15);
         int lblPaddleHeight = lblPaddle.Height;
         int lblPaddleXCoord = (screenWidth / 2) - (lblPaddleWidth / 2);
         int lblPaddleYCoord = screenHeight - lblPaddleHeight - (int)(screenHeight * 0.1);
         lblPaddle.SetBounds(lblPaddleXCoord, lblPaddleYCoord, lblPaddleWidth, lblPaddleHeight);

         this.Controls.Add(lblPaddle);
      }
   }

最终看起来像这样:

Scaled down screenshot

编辑:如果你打算用它做任何事情,我建议给它一个名字。我在上面添加了它。

答案 1 :(得分:0)

由于一些奇怪的原因,这不起作用。我和我学校的一位讲师谈过,她也无法弄清问题是什么。也许这是某种错误。我设法解决这个问题的唯一方法是创建另一个表单并创建另一个paddle,然后我将代码从我创建的表单复制到原始表单并且工作正常。我和讲师都无法弄清问题是什么。这很简单,因为代码基本相同。