用C#程序将控件添加到另一个Winform中

本文关键字:另一个 Winform 添加 控件 程序 | 更新日期: 2023-09-27 18:19:41

我现在有一个母表单,我想用程序创建一个新表单。我创建了新表单,但无法向表单添加控件。

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);
    }

我试过上面的代码,新表格显示了,但我看不到标签1。

我感谢任何帮助。

用C#程序将控件添加到另一个Winform中

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

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();
}

首先:将控件添加到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);
}