Partager via


How to: Detect Whether a Controller Is Disconnected

This example demonstrates how to detect whether an Xbox 360 Controller connected to the system at game start has become disconnected.

The example checks the IsConnected property of a retrieved GamePadState object. If the value is true, the controller is still connected, and the game continues. If the value is false, the controller has become disconnected, and the game will pause until the user reconnects the controller.

To detect whether a controller has been disconnected

  1. At program start, present an interface for users to choose which controllers are connected, and store this information. Proceed to the game loop.
  2. In the game loop, get the state of each Xbox 360 Controller by using GetState.
  3. Verify that each controller from the earlier list of connected controllers is still connected by retrieving the IsConnected property.
  4. If the current value of IsConnected is false for a previously connected controller, then the controller has become disconnected. Enter a pause loop and wait for the user to reconnect the controller.
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    ContentManager content;

    enum GameState
    {
        InputSetup = 0,
        Game,
        Disconnected
    }

    // Represent the current state of the game.
    GameState gameState = GameState.InputSetup;

    // Represent which controllers were connected at game start.
    bool[] activatedControllers = new bool[4];

    // Represent the current controller states.
    GamePadState[] gamePadStates = new GamePadState[4];

    // Represent the previous-frame controller states.
    GamePadState[] previousGamePadStates = new GamePadState[4];

    // Specify the maximum number of players.
    int maxPlayers = 4;

    public Game1()
    {
        graphics = new GraphicsDeviceManager( this );
        content = new ContentManager( Services );
    }

    protected override void Initialize()
    {

        base.Initialize();
    }

    protected override void LoadGraphicsContent( bool loadAllContent )
    {
        if (loadAllContent)
        {

        }

    }

    protected override void UnloadGraphicsContent( bool unloadAllContent )
    {
        if (unloadAllContent == true)
        {
            content.Unload();
        }
    }

    protected override void Update( GameTime gameTime )
    {
        // Allows the default game to exit on Xbox 360 and Windows
        if (GamePad.GetState( PlayerIndex.One ).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        switch (gameState)
        {
            case GameState.InputSetup:
                // Example setup of controllers.
                activatedControllers[0] = true; // Game will pause if Controller #1 is disconnected.
                activatedControllers[1] = false; // Game will not pause if Controller #2 is disconnected.

                // Allow players to choose their controllers.

                // When ready, proceed to the game.
                gameState = GameState.Game;
                break;
            case GameState.Game:
                // If disconnected, go to the disconnect loop.
                if (!UpdateInput())
                {
                    gameState = GameState.Disconnected;
                }
                break;
            case GameState.Disconnected:
                // If we are reconnected, go back to the game.
                if (UpdateInput())
                {
                    gameState = GameState.Game;
                }
                // Otherwise, display a message, pause, etc.
                break;
        }

        base.Update( gameTime );
    }

    public bool[] ControllersDisconnected()
    {
        bool[] disconnectedControllers = new bool[maxPlayers];
        bool anyDisconnected = false;
        for (int i = 0; i < maxPlayers; i++)
        {
            if (activatedControllers[i] == true && gamePadStates[i].IsConnected == false)
            {
                disconnectedControllers[i] = true;
                anyDisconnected = true;
            }
        }
        if (!anyDisconnected)
        {
            return null;
        }
        else
        {
            return disconnectedControllers;
        }
    }
    // Return false if the Player One controller is disconnected.
    public bool UpdateInput()
    {
        // Check the current states.
        gamePadStates[0] = GamePad.GetState( PlayerIndex.One );
        gamePadStates[1] = GamePad.GetState( PlayerIndex.Two );
        gamePadStates[2] = GamePad.GetState( PlayerIndex.Three );
        gamePadStates[3] = GamePad.GetState( PlayerIndex.Four );

        bool[] disconnectedControllers = ControllersDisconnected();
        if (disconnectedControllers != null)
        {
            return false;
        }
        else
        {
            // Process game input, and update previous controller states.
            previousGamePadStates[0] = gamePadStates[0];
            previousGamePadStates[1] = gamePadStates[1];
            previousGamePadStates[2] = gamePadStates[2];
            previousGamePadStates[3] = gamePadStates[3];
            return true;
        }
    }

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

        base.Draw( gameTime );
    }
}

See Also

How to: Detect Whether a Controller Button Is Pressed