Toggling Full Screen in XNA

December 2, 2009Josh Brown View Comments

If you don’t already know, the easy solution is to use this.Graphics.ToggleFullScreen() in your Game object.

While part of the solution, this should not be your entire solution.

Requirements:

  • Resizable viewport
  • Viewport size restored when returning from full screen
  • Full screen resolution should match the current resolution of the monitor
  • Support multiple monitors of different resolutions
  • Only toggle once per key press
  • Toggle full screen mode with Alt Enter or F4

Solution:

Firstly, I created a function that will determine the resolution of the monitor that the game window is currently on.  If it can’t find it, it will use the primary monitor’s resolution:

bool GetScreenBounds(out int Width, out int Height)
{
	foreach (var Screen in System.Windows.Forms.Screen.AllScreens)
	{
		if (String.Compare(Screen.DeviceName, this.Window.ScreenDeviceName, true) == 0)
		{
			Width = Screen.Bounds.Width;
			Height = Screen.Bounds.Height;
			return true;
		}
	}

	var Size = System.Windows.Forms.SystemInformation.PrimaryMonitorSize;
	Width = Size.Width;
	Height = Size.Height;
	return false;
}

Secondly, I built a method that I can call on every frame, providing it with the state of the toggle key.  It will determine if it should toggle or not.  It stores the window size when going from Windowed to Fullscreen and restores it when returning to Windowed.

bool FullScreenToggling = false;
int OldWidth, OldHeight;
void ToggleFullScreen(bool Toggle)
{
	if (Toggle && !FullScreenToggling)
	{
		if (!this.Graphics.IsFullScreen)
		{
			OldWidth = this.Graphics.GraphicsDevice.Viewport.Width;
			OldHeight = this.Graphics.GraphicsDevice.Viewport.Height;

			int NewWidth, NewHeight;
			GetScreenBounds(out NewWidth, out NewHeight);
			this.Graphics.PreferredBackBufferWidth = NewWidth;
			this.Graphics.PreferredBackBufferHeight = NewHeight;
		}
		else
		{
			this.Graphics.PreferredBackBufferWidth = OldWidth;
			this.Graphics.PreferredBackBufferHeight = OldHeight;
		}

		this.Graphics.ToggleFullScreen();
		FullScreenToggling = true;
	}
	else if (!Toggle && FullScreenToggling)
	{
		FullScreenToggling = false;
	}
}

Lastly, I call ToggleFullscreen in my Update method:

protected override void Update(GameTime GameTime)
{
	// Allows the game to exit
	if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
		this.Exit();

	ToggleFullScreen(
			( Keyboard.GetState().IsKeyDown(Keys.F4) ) ||
			( Keyboard.GetState().IsKeyDown(Keys.LeftAlt) && Keyboard.GetState().IsKeyDown(Keys.Enter)) );

	base.Update(GameTime);
}

Please note that you will have to add references to System.Windows.Forms and System.Windows.Drawing to your project.


blog comments powered by Disqus