C#: Get complete desktop size?

前端 未结 9 2043
梦谈多话
梦谈多话 2020-11-27 16:40

How do I find out the size of the entire desktop? Not the \"working area\" and not the \"screen resolution\", both of which refer to only o

相关标签:
9条回答
  • 2020-11-27 16:59

    Check:

    SystemInformation.VirtualScreen.Width
    SystemInformation.VirtualScreen.Height
    
    0 讨论(0)
  • 2020-11-27 17:02

    Get the Size of a virtual display without any dependencies

    public enum SystemMetric
    {
        VirtualScreenWidth = 78, // CXVIRTUALSCREEN 0x0000004E 
        VirtualScreenHeight = 79, // CYVIRTUALSCREEN 0x0000004F 
    }
    
    [DllImport("user32.dll")]
    public static extern int GetSystemMetrics(SystemMetric metric);
    
    public static Size GetVirtualDisplaySize()
    {
        var width = GetSystemMetrics(SystemMetric.VirtualScreenWidth);
        var height = GetSystemMetrics(SystemMetric.VirtualScreenHeight);
    
        return new Size(width, height);
    }
    
    0 讨论(0)
  • 2020-11-27 17:10

    I think it's time to bring this answer up to date with a little LINQ, which makes it easy to get the entire desktop size with a single expression.

    Console.WriteLine(
        Screen.AllScreens.Select(screen=>screen.Bounds)
        .Aggregate(Rectangle.Union)
        .Size
    );
    

    My original answer follows:


    I guess what you want is something like this:

    int minx, miny, maxx, maxy;
    minx = miny = int.MaxValue;
    maxx = maxy = int.MinValue;
    
    foreach(Screen screen in Screen.AllScreens){
        var bounds = screen.Bounds;
        minx = Math.Min(minx, bounds.X);
        miny = Math.Min(miny, bounds.Y);
        maxx = Math.Max(maxx, bounds.Right);
        maxy = Math.Max(maxy, bounds.Bottom);
    }
    
    Console.WriteLine("(width, height) = ({0}, {1})", maxx - minx, maxy - miny);
    

    Keep in mind that this doesn't tell the whole story. It is possible for multiple monitors to be staggered, or arranged in a nonrectangular shape. Therefore, it may be that not all of the space between (minx, miny) and (maxx, maxy) is visible.

    EDIT:

    I just realized that the code could be a bit simpler using Rectangle.Union:

    Rectangle rect = new Rectangle(int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);
    
    foreach(Screen screen in Screen.AllScreens)
        rect = Rectangle.Union(rect, screen.Bounds);
    
    Console.WriteLine("(width, height) = ({0}, {1})", rect.Width, rect.Height);
    
    0 讨论(0)
提交回复
热议问题