单击其他按钮时关闭以前的窗体

时间:2017-05-23 07:41:09

标签: c#

当我点击其他按钮时,我尝试在mdiparent中关闭窗体,结果是当我点击其他按钮时,它仍然会从新窗口的后面出现。那我怎么办呢?

private void btn_ic_Click(object sender, EventArgs e)
{

    pictureBox3.Visible = false;
    SelectIC ss = new SelectIC();
    ss.MdiParent = this;
    ss.Show();
    Detail aa = new Detail();
    aa.MdiParent = this;
    aa.Close();
    btn_ic.Enabled = false;
    btn_cat.Enabled = true;

}


private void btn_cat_Click(object sender, EventArgs e)
{
    pictureBox3.Visible = false;
    Detail aa = new Detail();
    aa.MdiParent = this;
    aa.Show();
    SelectIC ss = new SelectIC();
    ss.MdiParent = this;
    ss.Close();
    btn_cat.Enabled = false;
    btn_ic.Enabled = true;
}

1 个答案:

答案 0 :(得分:0)

您正在创建表单的新实例,然后关闭它。这样你就不会关闭现有的窗口,而是创建新的(不可见的)并关闭它。您应该在MdiChildren集合中找到现有窗口,然后将其关闭。像这样:

private void btn_ic_Click(object sender, EventArgs e)
{

    pictureBox3.Visible = false;
    SelectIC ss = new SelectIC();
    ss.MdiParent = this;
    ss.Show();

    var detailForm = this.MdiChildren.FirstOrDefault(f => f.GetType() == typeof(Detail));
    detailForm?.Close();

    btn_ic.Enabled = false;
    btn_cat.Enabled = true;

}

private void btn_cat_Click(object sender, EventArgs e)
{
    pictureBox3.Visible = false;
    Detail aa = new Detail();
    aa.MdiParent = this;
    aa.Show();

    var selectForm = this.MdiChildren.FirstOrDefault(f => f.GetType() == typeof(SelectIC));
    selectForm?.Close();

    btn_cat.Enabled = false;
    btn_ic.Enabled = true;
}