2

I have a C# Form, where you have Form1 shown at the start, and when you press Go you are taken to Form2. Form1 is hidden and Form2 is shown.

Now when you exit form2, the whole application should be closed. I am using Application.Exit() when I press the exit button. I am facing problems if the user presses X or ALT+F4 or RightClick->Close. The form will close but the hidden form will stay opened.

How can I fix that? When I press one of these control button, for all hidden forms to also close?

I tried form1_Close and Form1_Closing function but they didn't seem to work.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Nassif Bousaba
  • 386
  • 1
  • 4
  • 22

2 Answers2

6

Try this:

Hide();
Form2 form2 = new Form2();
form2.Closed += (s, args) => this.Close();
form2.Show();

This will close Form1 when you close Form2. If the user presses X or ALT+F4 or RightClick -> Close on Form2 The Form2 and the hidden Form1 will close.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
2

Use the FormClosed event on Form2 to exit the application.

private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
     Application.Exit();
}