user3527080
user3527080

Reputation: 3

How can I close the MainForm, without closing the others?

So, I'm writing a Hangman, and at the MainForm you have to choose if you want to play single player or multiplayer. When I choose which one I want, this MainForm should close( I use this.Close() ) and trigger another Form, but instead the entire program shuts down.

private void button2_Click(object sender, EventArgs e)
{
     Form f2 = new Form1();
     f2.Show();
     this.Close();           
}

If in Programs.cs I modify the code like this:

Form f4 = new Form4();
f4.Show();          
Application.Run();

everything goes well, but If I won't exit the program using Application.Exit(), it will still run in the background.

So, how could I solve this problem?

Upvotes: 0

Views: 446

Answers (3)

Grungondola
Grungondola

Reputation: 678

If you want a basic form that will pretty much just allow the user to play until they close the other form then close this form, use this:

private void button2_Click(object sender, EventArgs e)
{
    Form f2 = new Form1();
    this.Hide();
    f2.ShowDialog();
    this.Close();           
}

or something a bit more fancy will allow you to close the form if the user selects something like not wanting to play another game or change difficulty settings or whatever. You can do that like this:

private void button2_Click(object sender, EventArgs e)
{
    Form f2 = new Form1();
    this.Hide();
    if(f2.ShowDialog() == DialogResult.OK)
    {
        this.Show();
    }
    else
    {
        this.Close();
    }
}

Upvotes: 0

Zein Makki
Zein Makki

Reputation: 30052

You can't close the parent form and keep the children alive.

Use this.Hide() instead of this.Close()

Then on the Form2_FormClosed Event you can do Application.Exit() or you can even show the MainForm Again.

OR:

Form2 f2 = new Form2();
this.Visible = false;
f2.ShowDialog();
this.Close();

Upvotes: 2

Reza
Reza

Reputation: 19933

You can show (dialog) your form before Application.Run(new MainForm()), so you don't need to close the Mainform

Upvotes: 0

Related Questions