c# winform 从父窗口关闭子窗口

来源:百度知道 编辑:UC知道 时间:2024/09/22 22:29:27
代码如下:
private void button3_Click(object sender, EventArgs e)
{

Form form2 = new Form();

form2.Text = "子窗口";

Label lb = new Label();

string status = form2.WindowState.ToString();
lb.Text = status;

form2.Controls.Add(lb);

if (!this.isOpen)
{

form2.Show();
this.isOpen = true;
}
else
{
form2.hide();
this.isOpen = false;
}

}

ps: this.isOpen是主窗体类的一个私有字段。

实现的功能是点击父窗口的一个BUTTON控件弹出个新窗口,若已打开就关闭,没有打开就打开它。
注意是在只在一个BUTTON控件中判断。
我的代码不能实现,是否要用到windows api? api我是一窍不通。哪位大哥或大姐帮帮忙指教一下。
加了productSet.MdiParent = this;之后出错:
出错消息为:被指定为此窗体的

Application.OpenForms["Form2"].Dispose();

不需要API,不过你hide可不是关闭,只是隐藏了而已。你可以这样
bool isopen=false;
foreach (Form childrenForm in this.MdiChildren)
{
if (childrenForm.Name=="fatherName")//这里对你来说应该是form2
{
childrenForm.Visible = true;//如果你要求关闭的话就只要close就可以了,我现在是如果存在就显示,你可以参考一下,你也可以不
childrenForm.Activate();
isopen = true;
return;

}
}
if (!isopen)
{
FrmsetProduct productSet = new FrmsetProduct();
productSet.MdiParent = this;
productSet.WindowState = FormWindowState.Maximized;
productSet.Show();
}

}