How to: Exit a Game

This example demonstrates how to exit 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.
  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.
  3. Call the method in Game.Update and add an if block around the remaining code in update so that the code will not be executed if the method returned true.
  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.
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;

class Game1 : Microsoft.Xna.Framework.Game
{
    private GraphicsDeviceManager graphics;
    private GamePadState gamePadState;
    private KeyboardState keyboardState;

    protected override void Draw( GameTime gameTime )
    {
        graphics.GraphicsDevice.Clear( Color.CornflowerBlue );
        base.Draw( gameTime );

        // Add game-specific drawing code.
    }

    protected override void Update( GameTime gameTime )
    {
        gamePadState = GamePad.GetState( PlayerIndex.One );
        keyboardState = Keyboard.GetState();

        // If the ESC key is pressed, skip the rest of the update.
        if (exitKeyPressed() == false)
        {
            base.Update( gameTime );

            Simulate();
        }
    }

    void Simulate()
    {
        // Add game-specific logic.
    }

    bool exitKeyPressed()
    {
        // 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;
    }

    public Game1( )
    {
        graphics = new GraphicsDeviceManager( this );
        this.Exiting += new EventHandler( SimpleGameLoop_Exiting );
    }

    void SimpleGameLoop_Exiting( object sender, EventArgs e )
    {
        // Add any code that must execute before the game ends.
    }
}