如何关闭一个 activeMidForm 并打开另一个?

How to close an activeMidForm and open another?

我有一个方法可以使用打开一个 Mid Child。

假设我在一个名为 "InventoryAdd" 的表单上,在此表单上我有一个下拉菜单。当用户从菜单中选择值“-1”时,我想打开另一个(即 DepartmentsAdd())。然后在 DepartmentAdd 打开后我想关闭 InventoryAdd 表单。

这是 InventoryAdd 表单菜单背后的代码

private void InputDepartment_SelectedValueChanged(object sender, EventArgs e) {
    //InputDepartment.ValueMember = "ID";
    int selectedDept = Convert.ToInt32(InputDepartment.SelectedValue);

    if (selectedDept == -1) {
        Form myForm = this.ActiveMdiChild;

        Common.OpenMyForm("Vendors", new string[] { "add" }, new DepartmentsAdd());

        if (myForm != null) {
            myForm.Close();
        }
    }
}

这个方法打开新的中间形式

    public static void OpenMyForm(string sectionName, string[] keys, Form myform) {
        //make sure there are no other forms of the ame type open
        foreach (Form form in Application.OpenForms) {
            if (form.GetType() == myform.GetType()) {
                form.Activate();
                return;
            }
        }

        if (Settings._AuthenticationMode == "Thumbprint") {

            var newMDIChild = myform;

            // Set the Parent Form of the Child window.
            newMDIChild.MdiParent = AppContext.CurrentContext.MainForm;

            // Display the new form.
            newMDIChild.Show();
        }


        if (Settings._AuthenticationMode == "Single" && UserInfo.Autherized == true) {

            var role = new Roles();

            if (role.hasAccess(sectionName, keys)) {
                var newMDIChild = myform;

                // Set the Parent Form of the Child window.
                newMDIChild.MdiParent = AppContext.CurrentContext.MainForm;

                // Display the new form.
                newMDIChild.Show();
            }
            else {
                Common.Alert("You do not have a permissions to perform this action!");
            }
        }
    }
}

我的代码打开 Mid 窗体没有任何问题。但是,"InventoryAdd" 表单永远不会关闭。 "myForm" 永远不会关闭它。

如何正确关闭 Mid 窗体?

谢谢

如果您在调用上下文中为新打开的表单设置 shown 的事件侦听器,您可以让现有表单在其子项打开后自行关闭。

Form myForm=new Form();
myForm.shown += closeForm;
...

void closeForm(object sender, EventArgs e){
this.Dispose(); // as long as within the previous           forms context.
}
myForm.Close();

正在关闭程序尝试使用

myForm.Hide();