Home > database >  Form remains open in the background after closing it
Form remains open in the background after closing it

Time:11-15

Edit : Question Solved

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. I'm new to C# programming.

CodePudding user response:

When you write:

 Form1 x = new Form1();

you are creating a new Form1, 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.

  •  Tags:  
  • c#
  • Related