Search code examples
c#formsexit-codeformclosing

Application.Exit() - application still running after closing form


I have a game application in which when the game form is closed, a main menu always pops up.. therefore, all the application is supposed to stop running when a user closes the main menu form. I am trying to handle the Form_Closed event for the main menu and do Application.Exit() however this doesn't seem to work even if all the forms are closed, the application is still running and I have to stop it manually.

This is the code I have in Game Form and Main Menu Form regarding closing:

IN GAME FORM:

private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
    DialogResult dialogResult = MessageBox.Show("Are you sure you want to close this game?", "Exit Game", MessageBoxButtons.YesNo);

    if (dialogResult == DialogResult.Yes)
    {
        this.Hide();   // hide the Game Form

    }
    else if (dialogResult == DialogResult.No)
    {
        e.Cancel = true;    // cancel form closure
    }

}

private void GameForm_FormClosed(object sender, FormClosedEventArgs e)
{
    MainMenu menu = new MainMenu();
    menu.Show();
}

AND IN MAIN MENU FORM:

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

Am I doing something wrong, or is there something I should add for this to work?


Solution

  • Considering that you are talking about gaming application, you make use of external resources or some game engine. Before exit from application, make sure you free/dispose/clean-up resources you used in your app.

    For example to keep track of open handles may use Handle