Reputation: 3790
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();
}
}
Upvotes: 0
Views: 5146
Reputation: 16190
I'd use
if (form2 == null)
{
form2 = new Form2();
form2.FormClosed += (s, e) => { this.form2 = null; };
form2.Show();
}
form2.BringToFront()
So every time form2
is closed, the reference is set to null
. Next time it can be re-instantiated.
As long as it is still there, bring it to front.
Upvotes: 3
Reputation: 203820
You don't need to have Form2
handle the closing event, you can just do it directly from Form1
:
private Form2 form2;
private void button1_Click(object sender, EventArgs e)
{
if (form2 == null)
{
form2 = new Form2();
form2.FormClosed += (_, arg) =>
{
form2 = null;
};
form2.Show();
}
else
{
//the other form has been opened and not closed; not sure what you want to do
}
}
Also note that if a form is shown via Show
you don't need to dispose of it. If you show it via ShowDialog
then 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.
Upvotes: 6
Reputation: 4328
If you're showing the form, the form will thrown an event called Form.Shown
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.shown.aspx
You can put some sort of handling code there (even if its just setting a flag). Similarly there's a form closing/closed event if the user closes it.
I THINK there's a formloaded event too, but I can't remember off the top of my head.
Upvotes: 0
Reputation: 13399
You can pass Form1 to Form2 and in the events like .Loaded or while disposing/exiting in the Form2, you can use the Form1 object to let it know that those events have happened.
Upvotes: 0