samyarkhafan
samyarkhafan

Reputation: 17

Form remains open in the background after closing it

So I want to show a form and close the other form so I did this in form1:

    private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
{
    Form2 x = new Form2();
    x.Show();
    this.Hide();
    //didn't use this.close() cause then the whole program will close instead of 
    //just the current form
}

Then I wanted the main form to open again after the 2nd form is closed so I did this in form2:

private void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        Form1 x = new Form1();
        x.Show();
    }

Now the problem is when I'm back in the main form after closing the 2nd form. if I close the main form it doesn't fully close and still remains open in the background (I found it in task manager). I think its because the "show" method just opens another form instead of making the form appear so the main form which got hidden is still there running in the background. what should I do to make the form get closed when I exit it? I tried putting this.close(); in the form closed and form closing event but both resulted in a crash.

Upvotes: 1

Views: 795

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39142

Another option is to simply subscribe to the FormClosed() event of Form2 when you create it, then un-hide your instance of Form1 from there:

// ... all in Form1 ...

private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
{
    this.Hide();
    Form2 x = new Form2();
    x.FormClosed += X_FormClosed;
    x.Show();
}

private void X_FormClosed(object sender, FormClosedEventArgs e)
{
    this.Show();
}

So then when you close Form2 your instance of Form1 will automatically re-appear.

Upvotes: 0

Michael Haddad
Michael Haddad

Reputation: 4445

When you write:

 Form1 x = new Form1();

you are creating a new Form1 object, so x refers to the new one and not to the original one. Instead, you could use this:

private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
{
    using (var form2 = new Form2())
    {
        this.Hide();
        form2.ShowDialog();
    }
    this.Show();
}

When ShowDialog() is called, the code following it is not executed until after the dialog box is closed, so this.Show() will execute only after Form2 is closed.

Upvotes: 2

Related Questions