Search code examples
c#.netwindowsgdi

Windows screenshot with scaling


I am trying to take screenshots of every screen on my windows 10 machine. My system has 2 monitors which are of multiple DPIs.

  • My primary monitor has "scale and layout" set to 200%.
  • My secondary has "scale and layout" set to 100%. enter image description here

I am trying to use C# to take a screenshot of every single monitor. However my scaled monitor is reporting the wrong coordinates: Everything is halved. As a result, the primary monitor's screenshot is only 1/4th of the screen area (width/2,height/2).

Here is my code:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;

namespace CsSourceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Screen[] screens;
            screens = Screen.AllScreens;


            int i = 0;

            foreach (var screen in System.Windows.Forms.Screen.AllScreens)
            {
                var savePath = "monitor" + i+".jpg";
                var x = screen.Bounds.Location.X;
                var y = screen.Bounds.Location.Y;
                var w = screen.Bounds.Width;
                var h = screen.Bounds.Height;
                Console.Out.WriteLine("Monitor: " + i + " extents:" + x + "," + y + " " + w + "," + h);
                using (Bitmap bmp = new Bitmap(w, h))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.CopyFromScreen(x, y, 0, 0, bmp.Size);
                    }

                    bmp.Save(savePath, ImageFormat.Jpeg);
                    Console.Out.WriteLine("saved: " + savePath);
                }
                i++;
            }



        }
    }
}

PS: I get different values based on what I set "dpiaware" in the manifest file: https://social.msdn.microsoft.com/Forums/en-US/054c1d49-9f24-4617-aa83-9bc4f1bb4a5d/use-appmanifest-file-to-make-winforms-application-dpi-aware?forum=vbgeneral

If I don't set dpiaware, then the primary monitor's bounds get halved (cropping out 3/4ths of the screen). If I set dpiaware to true, then the secondary monitor's bounds get doubled (leaving big black areas in the screenshot).


Solution

  • As mentioned in the comments, the solution is to set the app.manifest dpiAware tag to "true/pm". The effect is different than just setting it to true.

    <application xmlns="urn:schemas-microsoft-com:asm.v3">
        <windowsSettings>
          <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
        </windowsSettings>
      </application>