Have you ever wanted to be able to take screenshots of your game? In this tutorial I will show you how to create a screenshot system in which, when the player press PrintScreen key the game will create the screenshot and save it to a folder. The only problem is that SFML does not support the PrintScreen key, so we can’t check if the PrintScreen key is pressed and instead of this we will use another key, the F5 key.

The code is simple to follow: we check if the F5 key is pressed, if yes we take a screenshot of the window by calling the function capture() which we save to a sf::Image and export the sf::Image to an image file in a folder named “screenshots”. The file name will be the actual date and actual time of the system when the screenshot will be taken.

#include <SFML/Graphics.hpp>
#include <iostream>
#include <ctime>

int main()
{
	sf::RenderWindow window(sf::VideoMode(800,600), "Screenshot System");

	while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();

            if (event.type == sf::Event::KeyPressed)
            {
            	if (event.key.code == sf::Keyboard::F5)
                {
                    // Capturing the window to a sf::Image
                    sf::Image screenshot = window.capture();

                    // Getting the actual time
                    time_t epoch_time;
                    struct tm *tm_p;
                    epoch_time = time( NULL );
                    tm_p = localtime( &epoch_time );

                    // Making the screenshot name
                    std::string screenshotName = std::to_string(tm_p->tm_mday) + "-" + std::to_string(tm_p->tm_mon) + "-" + std::to_string(tm_p->tm_year) + " " + std::to_string(tm_p->tm_hour) + std::to_string(tm_p->tm_min) + std::to_string(tm_p->tm_sec);

                    // Saving to a file
                    screenshot.saveToFile("screenshots/"+screenshotName+".png");   
                }
            }
        }

        window.clear();
        window.display();
    }

    return 0;
}

We are using the ctime/time.h library to take the system time and a good alternative to this is using the boost library.

An improvement to the system is doing everything in another thread. In this way the game performance will be not affected.

Another improvement is checking if the “screenshots” folder exist because otherwise, if the folder does not exist (it may be deleted by the player), the game will be not able to save the image.

You can find the source code and the resources on GitHub: