Detect when a child form is closed

I have he following Form:

  • An Initialize Function that is called when the Form1 is created.
  • A button that opens another Form (Form2)

What I need is to call Initialize() not only when Form1 is created, but whenever Form2 is closed, since Form2 might have modified some stuff that makes Initialize need to be called again.

How can I detect when the form2 is closed?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Initialize();
    }

    void Initialize()
    {
        // Read a config file and initialize some stuff
    }

    // Clicking this button will open a Form2
    private void button1_Click(object sender, EventArgs e)
    {
        var form2 = new Form2().Show();
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
        // some stuff that Form2 does which involves modifying the config file
    }
}

>Solution :

You just need to add an event handler for the FormClosing event, this handler could be in your first form class and here you can call every internal method of that class

private void button1_Click(object sender, EventArgs e)
{
    var form2 = new Form2();
    form2.FormClosing += childClosing;
    form2.Show();
}
private void childClosing(object sender, FormClosingEventArgs e)
{
    Initialize();
    ....
}

Leave a Reply