Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

How To: Exit a Game

This example demonstrates how to exit a game without finishing the current update.

The Complete Sample

The code in this tutorial illustrates the technique described in the text. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.

To Exit the Game Loop without Running any Remaining Code in the Update Handler

  1. Derive a class from Game.
  2. Create a method that checks KeyboardState.IsKeyDown for the state of the ESC key. 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)
            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))
  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

© 2015 Microsoft