In these days I needed to capture the screen in a Windows application I’m developing in C#.

Looking on the Internet, I found several solutions to the problem, but all of them had a defect: they did not work properly if the scale was set a value higher than 100%, as you can see below:

Display Settings

With a scale higher than 100%, the code I found was not able to get the entire screen but only a portion, because Windows, in this case, sets a virtual screen size that is lower than the physical one. The virtual screen size is the one used to create the snapshot.

So, based on the code found on the internet, I developed my own class to capture the screen, and today I want to share it with you:

public class ScreenCapture
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr GetDesktopWindow();

    private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

    private enum DeviceCap
        DESKTOPVERTRES = 117,
        DESKTOPHORZRES = 118

    public static Bitmap CaptureDesktop()
        Bitmap ScreenBitmap;
        IntPtr DesktopHwnd = GetDesktopWindow();
        using (Graphics DesktopGr = Graphics.FromHwnd(DesktopHwnd))
            IntPtr DesktopHdc = DesktopGr.GetHdc();
            int XRes = GetDeviceCaps(DesktopHdc, (int)DeviceCap.DESKTOPHORZRES);
            int YRes = GetDeviceCaps(DesktopHdc, (int)DeviceCap.DESKTOPVERTRES);

            ScreenBitmap = new Bitmap(XRes, YRes);

            using (Graphics ScreenBitmapGr = Graphics.FromImage(ScreenBitmap))
                 ScreenBitmapGr.CopyFromScreen(0, 0, 0, 0, new Size(XRes, YRes));

        return ScreenBitmap;

Why this code works?

It works because to get the screen size, it uses the Windows function “GetDeviceCaps” called two times: one for the horizontal size and one for the vertical size. Using the options DESKTOPHORZRES and DESKTOPVERTRES the function GetDeviceCaps return the actual size of the screen that you can use to create the snapshot.

Click here to download the full project developed with Visual Studio 2019 Community.

If you want to use it, remember to change the path where to save the snapshot.

Moreover, the application provides a label showing the current mouse coordinates. With a scale higher than 100%, if you bring the mouse pointer in the lower right corner of the screen, you will see that the coordinates do not reflect those of the actual screen size.

See you next year!

Bye bye!!