Export (0) Print
Expand All

How To: Exit a Game

Demonstrates how to exit a game without finishing the current update.

The Complete Sample

The code in this topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Exiting a Game Without Finishing the Current Update

To exit the game loop without running any remaining code in the update handler

  1. Derive a class from Game.

    You need to create a method that checks KeyboardState.IsKeyDown for the state of the ESC key.

  2. If the ESC key has been pressed, call Game.Exit and return true.

    bool checkExitKey(KeyboardState keyboardState, GamePadState gamePadState)
    {
        // Check to see whether ESC was pressed on the keyboard or BACK was pressed on the controller.
        if (keyboardState.IsKeyDown(Keys.Escape) || gamePadState.Buttons.Back == ButtonState.Pressed)
        {
            Exit();
            return true;
        }
        return false;
    }
    
  3. Call the method in Game.Update, and return from Update if the method returned true.

    // Check to see if the user has exited
    if (checkExitKey(keyboardState, gamePadState))
    {
        base.Update(gameTime);
        return;
    }
    
  4. Create a method to handle the Game.Exiting event.

    The Exiting event will be issued at the end of the tick in which Game.Exit is called.

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        ...
        this.Exiting += new EventHandler(Game1_Exiting);
        ...
    }
    
    void Game1_Exiting(object sender, EventArgs e)
    {
        // Add any code that must execute before the game ends.
    }
    

Community Additions

ADD
Show:
© 2014 Microsoft