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.
You can use KeyDown
event 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();
}
}