我认为是时候用一点 LINQ 来更新这个答案了,这样可以很容易地用一个表达式来获得整个桌面大小。
Console.WriteLine(
Screen.AllScreens.Select(screen=>screen.Bounds)
.Aggregate(Rectangle.Union)
.Size
);
我的原始答案如下:
我猜你想要的是这样的:
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);
请记住,这并不能说明全部情况。多个显示器可以交错排列,或者排列成非矩形。因此,可能不是 (minx, miny) 和 (maxx, maxy) 之间的所有空间都是可见的。
编辑:
我刚刚意识到使用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);