1

我现在有母亲表格,我想以编程方式创建一个新表格。我创建了新表单,但无法向表单添加控件。

private void CreateWindows()
    {
        newWindow = new Form();
        Application.Run(newWindow);

        newWindow.Activate();

        newWindow.Size = new System.Drawing.Size(40, 40);

       Label label1 = new Label();

       newWindow.Controls.Add(label1);  

       label1.Text = "HI";
       label1.Visible = true;
       label1.Size = new System.Drawing.Size(24, 24);
       label1.Location = new System.Drawing.Point(24, 24);

    }

我已经尝试了上面的代码,显示了新表单,但我看不到 label1。

我很感激任何帮助。

4

2 回答 2

3

在设置标签的属性后尝试放置添加控件,然后显示新窗口。

private void CreateWindows()
{
    newWindow = new Form();

    newWindow.Activate();

    newWindow.Size = new System.Drawing.Size(40, 40);

   Label label1 = new Label();


   label1.Text = "HI";
   label1.Visible = true;
   label1.Size = new System.Drawing.Size(24, 24);
   label1.Location = new System.Drawing.Point(24, 24);

   newWindow.Controls.Add(label1);  
   newWindow.Show();
   //use this if you want to wait for the form to be closed
   //newWindow.ShowDialog();

}
于 2013-06-25T03:24:33.287 回答
1

首先:将控件添加到newWindow.Controls.

第二:先做,Application.Run因为它会显示表单,然后等待它关闭(注意:设计者这样做的方式是将它们添加到从Form派生的类的构造函数中)。

private void CreateWindows()
{
    newWindow = new Form();
    //Application.Run(newWindow); //Not here

    //newWindow.Activate(); //Wont do anything

    newWindow.Size = new System.Drawing.Size(40, 40);

    Label label1 = new Label();

    newWindow.Controls.Add(label1); //Good

    label1.Text = "HI";
    label1.Visible = true;
    label1.Size = new System.Drawing.Size(24, 24);
    label1.Location = new System.Drawing.Point(24, 24);

    Application.Run(newWindow); //Here instead
}

第三:如果你已经Application.Run在当前线程中使用过(比如说因为你是从一个表单中进行的),那么这里调用它是没有意义的。使用ShowShowDialog代替。


还可以考虑以这种方式添加控件:

private void CreateWindows()
{
    newWindow = new Form();
    newWindow.Size = new System.Drawing.Size(40, 40);

    newWindow.Controls.Add
    (
        new Label()
        {
            Text = "HI",
            Visible = true,
            Size = new System.Drawing.Size(24, 24),
            Location = new System.Drawing.Point(24, 24)
        }
    );
    Application.Run(newWindow);
}
于 2013-06-25T03:32:56.780 回答