Taking screenshots in XNA

imageWouldn’t it be nice if it was simple to add screenshot functionality to your games? People who play your games could easily post pictures online, gathering even more interest in and publicity for your game? Smiley

I’ve gathered some screenshot code I found on the web (credits in the code) in a little GraphicsDevice extension method. If you aren't familiar with extension methods, basically they add new functionality to existing classes - in this case adds two new methods to Microsoft's GraphicsDevice class.

class diagram

The class is here C# (right click > "save as..."), or ZIP.
Complete codesample here.

To use it :

  1. add the GraphicsDeviceExtensions class to your project
  2. call the GraphicsDevice.PrepareScreenshot() before the spriteBatch.Begin()
  3. call the GraphicsDevice.SaveScreenshot() after spriteBatch.End()

If you pass the SaveScreenshot method a filename or path then that filename will be used. If you don’t then screendumps will be saved in a file called Screenshot_001.png, Screenshot_002.png, etc. in the running game’s folder.

In the code sample below, the screenshot is prepared on line 9 and the screenshot is taken on line 34.

bool doScreenshot = false;  //set this to true to perform screenshot

protected override void Draw(GameTime gameTime)

    //if necessary, we prepare for a screenshot 
    if (doScreenshot)

    //Clear graphicsdevice with blue background

    //begin drawing

    //write test string
    spriteBatch.DrawString(_defaultFont, "Screenshot test!", new Vector2(100, 100), Color.Red);

    //write whether we are running in HiDef or Reach graphics profile
    spriteBatch.DrawString(_defaultFont, "Profile: " + graphics.GraphicsProfile,
        new Vector2(100, 200), Color.DarkRed);

    //call superclass' Draw()

    //end drawing 

    //if necessary, we save the image to a screenshot
    if (doScreenshot)
        doScreenshot = false;

4 Responses to “Taking screenshots in XNA”

  1. joppiesaus Says:

    This is a awsome class! But this is a bit weird, because you get automaticly a purple screen when you take a screenshot.

  2. admin Says:

    Okay, that sounds like you're not calling GraphicsDevice.PrepareScreenShot _before_ SpriteBatch.Begin, and GraphicsDevice.SaveScreenShot _after_ SpriteBatch.End ....?
    Have you tried downloading the codesample and comparing it with your code?
    If you're still at a loss to the purple screen, send me the code for your Draw() method - my email is: "kr [at] rup [dot] dk" and I'll have a look at it :)

    Kind regards - Jakob

  3. Kai Andres Says:

    When i try to create 1++ screenshots its everytime the same shot even if the drawing has moved.

  4. admin Says:

    Hi Kai :)

    Would you mail me your code to look at?

    Kind regards - Jakob

Leave a Reply