1

I have 2 forms, form1 is the menu, with the buttons start, settings, quit, and form2 is where the program will run.

The problem I face is that if the user uses Alt+F4 on form2, it closes form2, but form1 runs in the background. I know I can use the form2 Closing event, so it can run an Environment.Exit(0), but that closing event also "activates" if I use the form2 "Back to Menu" button, which closes form2. I also tried just hiding form2 with the Menu button, but then when I need to call another form2, it opens up a new instance of it.

So, in summary: ALT+F4 should close the whole application, not just the current form, but can't use form2 Closing event, because I want to close form2 some other way too.

MicroVirus
  • 5,324
  • 2
  • 28
  • 53
Drake
  • 111
  • 1
  • 8
  • 1
    Well, you could use the `KeyDown` event to detect the `Alt+F4`combination and act accordingly – Pikoh Jun 10 '16 at 11:04

1 Answers1

1

You can use KeyDownevent for that. Basically, you catch that key combination, tell the system that you are going to process it so it does not get passed to it and finally close the application. To close it, is always better to use Application.Exit() instead of Environment.Exit. You can see why here for example:

    private void Form2_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Alt && e.KeyCode == Keys.F4)
        {
            e.Handled = true;
            //Close your app
            Application.Exit();
        }
    }
Community
  • 1
  • 1
Pikoh
  • 7,582
  • 28
  • 53
  • `Environment.Exit` should be used as last resort as it forcibly and abruptly terminates the program immediately. – Lasse V. Karlsen Jun 10 '16 at 11:28
  • @LasseV.Karlsen you are right. I just used the method OP proposed to close the application and didn't thought about it. – Pikoh Jun 10 '16 at 11:29
  • Thanks! And Lasse V. Karlsen, I know what it does, but when someone presses the ALT+F4 they really want to close the app. I handle the Quit button properly. – Drake Jun 10 '16 at 11:31