代码之家  ›  专栏  ›  技术社区  ›  Jason Von Ruden

如何在Windows Forms 2.0中从子窗体关闭父窗体?

  •  3
  • Jason Von Ruden  · 技术社区  · 17 年前

    7 回复  |  直到 17 年前
        1
  •  5
  •   Jason Von Ruden    17 年前

    我无意中看到了这篇博客文章,它看起来会起作用,它使用了D2VIANT Answer中的事件处理程序概念

    http://www.dotnetcurry.com/ShowArticle.aspx?ID=125

    总结: 步骤1:创建新的Windows应用程序。打开VisualStudio2005或2008。转到文件>新>项目>在“项目类型”中选择Visual Basic或Visual C>Windows应用程序。为项目提供名称和位置>好啊

    步骤2:添加一个n

    步骤3:现在在表单1中,拖放一个按钮btnOpenForm并双击它以生成事件处理程序。在其中编写以下代码。还添加frm2_FormClosed事件处理程序,如下所示:

        private void btnOpenForm_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);
            frm2.Show();
            this.Hide();
        }
    
    
        private void frm2_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Close();
        }
    
        2
  •  3
  •   aku    17 年前

    当您在WinForms中关闭窗体时,它将处理它的所有子项。所以这不是个好主意。您需要异步执行此操作,例如,您可以向父窗体发送消息。

        3
  •  0
  •   dguaraglia    17 年前

        4
  •  0
  •   D2VIANT    17 年前

    也许考虑让父对象订阅一个事件,并且当孩子想要关闭父对象时,该事件可以触发该事件。然后,父对象可以处理自己的关闭(以及子对象的关闭)。

        5
  •  0
  •   chrissie1    17 年前

    您显然没有使用正确的方式打开和关闭表单。如果您使用任何形式的MVC或MVP,则不会出现此问题。

        6
  •  0
  •   Ed Schwehm    17 年前

    我同意大卫的观点;您可以将对父窗体的引用添加到子窗体的构造函数中,然后根据需要关闭父窗体:

    private Form pForm;
    public ChildForm(ref Form parentForm)
    {
        pForm = parentForm;
    }
    
    private closeParent()
    {
        if (this.pForm != null)
            this.pForm.Close();
        this.pForm = null;
    }
    
        7
  •  0
  •   Keyur Sureliya    8 年前

    有一个非常简单的解决方案。

    问题(请确定):启动应用程序(主窗体)>通过按钮或任何事件打开主窗体的子窗体>关闭(主窗体),但子窗体也关闭。

    解决方案:

    Process.Start("Your_App's_EXE_Full_Path.exe");

    示例:尝试以下操作以获取完整路径:

    1. string FullPath = Environment.CurrentDirectory + "\\YourAppName.exe";

    2. Process.Start(FullPath); .

    3. this.Close();

    推荐文章