I have 2 Forms in my app, Form1 and Form2. I want to know if there is a
better way of checking if the form has already been loaded. If the form is
loaded in memory and visible, I want the button to do nothing, if the User
has closed the form it should re-instantiate it.
For more info check my code or comment.. 🙂
public partial class Form1: Form
{
private Form2 form2;
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
if (form2== null) {
form2= new Form2();
} else {
if (form2.has_exited()) { // this is a private property
// that I set when Form2.Closing executes
form2.Dispose();
form2= new Form2();
}
}
form2.Show();
}
}
You don’t need to have
Form2handle the closing event, you can just do it directly fromForm1:Also note that if a form is shown via
Showyou don’t need to dispose of it. If you show it viaShowDialogthen you do, but when you use the non-modal dialog the system will automatically attach an event handler to the closing event that calls dispose.