C# 如何在Windows窗体中按其子级更改父级大小?

C# 如何在Windows窗体中按其子级更改父级大小?,c#,winforms,size,parent,C#,Winforms,Size,Parent,在父窗体中,我有一个命令,在主窗体中添加一个子窗体: AddChildForm(new Form2()); 在我的Form2中,我有一个复选框,每次选中该复选框时,我都必须更改我的主窗体大小,但我无法进行此工作,只能创建一个新窗体,如下所示: Form1 main = new Form1(); main.Size = new System.Drawing.Size(482, 370); main.ShowDialog(); AddChildForm(new Form2(this)); /

在父窗体中,我有一个命令,在主窗体中添加一个子窗体:

 AddChildForm(new Form2());
在我的Form2中,我有一个复选框,每次选中该复选框时,我都必须更改我的主窗体大小,但我无法进行此工作,只能创建一个新窗体,如下所示:

Form1 main = new Form1();
main.Size = new System.Drawing.Size(482, 370);
main.ShowDialog();
AddChildForm(new Form2(this));  //  <--- pass in reference to the opening form!
Form1 mainForm = null;

public Form2(Form1 form1)   // here we receive the main form reference
{
    InitializeComponent();
    mainForm = form1;      // here we store it in a class level variable
    //..
}

如果您不想要新的
表单1
,请不要创建它

您可能需要对真正的主窗体进行引用。这应该在打开它的过程中或之后的某个时间设置,但由于您向我们显示的只是4行上下文无关的行,我们无法确定

由于我们没有看到
AddChildForm
代码,因此更难猜测

但是,您可能需要将打开的表单的引用传递到打开的表单,如下所示:

Form1 main = new Form1();
main.Size = new System.Drawing.Size(482, 370);
main.ShowDialog();
AddChildForm(new Form2(this));  //  <--- pass in reference to the opening form!
Form1 mainForm = null;

public Form2(Form1 form1)   // here we receive the main form reference
{
    InitializeComponent();
    mainForm = form1;      // here we store it in a class level variable
    //..
}
现在,您可以设置其他窗体的大小:

mainForm.Size = new System.Drawing.Size(482, 370);
当然,如果需要,您也应该在主窗体中保留对正在打开的窗体的引用。为此,请使用类似以下内容:

Form2 form2 = new Form2(this);
..

AddChildForm( form2);

我建议您不要让Form2更改Form1,而是让Form2通知Form1它需要更改。查看匿名事件处理程序。