我想用delegate来控制关闭子窗口时同时关闭父窗口,在子窗口的form_closed()函数中通过delegate实例调用父窗口中的closeit()方法(该方法会关闭父窗口),但是关闭子窗口时出现stackoverflow异常,于是我在父窗口的closeit()中this.Close()之前加入MessageBox.Show("closing");发现会无限弹出信息,不知道是什么原理(取消两窗口的mdi关联以后该问题消失,但是有什么其他方法解决这个问题吗?)

解决方案 »

  1.   

    不用 delegate就可以实现,代码如下:
    主窗体:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;namespace WindowsFormsApplication13
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();            Form2 f = new Form2();
                f.Show();
            }
            public static void close()
            {
                Application.Exit();
            }
            
        }
    }
    子窗体:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;namespace WindowsFormsApplication13
    {
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
            private void button1_Click(object sender, EventArgs e)
            {
                this.Close();
                Form1.close();
            }
        }
    }
      

  2.   


    窗口本来就有Closing、Closed事件。画蛇添足没有必要!
      

  3.   

    子窗口中加一个 bool 变量,初始值为 false,在 form_closed 事件方法中加入判断
    if (变量为 False)
    {
        变量 = true;
        closeit()
    }
    让父窗口的关闭方法只执行一次,免得无限递归
      

  4.   

    这样的话还是存在那个问题,会无限循环。我猜是因为在子窗体的form_closed()中调用父窗体的Close()时,父窗体会先关闭所有的mdichildren,执行关闭所有子窗体的命令,这样子窗体中的form_closed()方法就会再会被调用一遍