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
}
}
CodePudding user response:
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();
....
}
CodePudding user response:
In addition to Steve's excellent answer, you may consider displaying Form2 as a modal dialog. This would mean code execution in Form1 STOPS until Form2 is dismissed. This may or may not work well with your application, we have no idea what it does.
At any rate, you'd use ShowDialog() instead of Show()
like this:
// Clicking this button will open a Form2
private void button1_Click(object sender, EventArgs e)
{
var form2 = new Form2().ShowDialog(); // <-- code STOPS here until form2 is closed
Initialize(); // form2 was closed, update everything
}