C#:获取完整的桌面大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1317235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:04:19  来源:igfitidea点击:

C#: Get complete desktop size?

c#.netdesktopscreenscreen-resolution

提问by Timwi

How do I find out the size of the entire desktop? Notthe "working area" and notthe "screen resolution", both of which refer to only one screen. I want to find out the total width and height of the virtual desktop of which each monitor is showing only a part.

如何找出整个桌面的大小?不是“工作区域”也不是“屏幕分辨率”,两者都只指一个屏幕。我想找出每个显示器只显示一部分的虚拟桌面的总宽度和高度。

采纳答案by Dennis

You have two options:

您有两个选择:

  1. PresentationFramework.dll

    SystemParameters.VirtualScreenWidth   
    SystemParameters.VirtualScreenHeight
    
  2. System.Windows.Forms.dll

    SystemInformation.VirtualScreen.Width   
    SystemInformation.VirtualScreen.Height
    
  1. 演示框架.dll

    SystemParameters.VirtualScreenWidth   
    SystemParameters.VirtualScreenHeight
    
  2. 系统.Windows.Forms.dll

    SystemInformation.VirtualScreen.Width   
    SystemInformation.VirtualScreen.Height
    

Use the first optionif you developing a WPF application.

如果您开发 WPF 应用程序,请使用第一个选项

回答by P Daddy

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.

我认为是时候用一个小的 LINQ 更新这个答案了,这使得用一个表达式很容易获得整个桌面大小。

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.

请记住,这并不能说明全部情况。多个显示器可以交错排列,或排列成非矩形形状。因此,可能并非 (minx, miny) 和 (maxx, maxy) 之间的所有空间都是可见的。

EDIT:

编辑:

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

我刚刚意识到使用以下代码可能会更简单一些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);

回答by TechStuffBC

This doesn't answer the question, but merely adds additional insight on a window's Point (location) within all the screens).

这并没有回答问题,而只是增加了对所有屏幕中窗口点(位置)的额外了解。

Use the code below to find out if a Point (e.g. last known Location of window) is within the bounds of the overall Desktop. If not, reset the window's Location to the default pBaseLoc;

使用下面的代码找出一个点(例如窗口的最后一个已知位置)是否在整个桌面的范围内。如果不是,则将窗口的 Location 重置为默认的pBaseLoc

Code does not account for the TaskBar or other Toolbars, yer on yer own there.

代码不考虑任务栏或其他工具栏,你自己在那里。

Example Use: Save the Window location to a database from station A. User logs into station Bwith 2 monitors and moves the window to the 2nd monitor, logs out saving new location. Back to station Aand the window wouldn't be shown unless the above code is used.

使用示例:将 Window 位置从A 站保存到数据库。用户使用 2 个监视器登录B 站并将窗口移动到第二个监视器,注销保存新位置。回到A 站,除非使用上述代码,否则不会显示窗口。

My further resolve implemented saving the userID and station's IP (& winLoc) to database or local user prefs file for a given app, then load in user pref for that station & app.

我的进一步解决方案是将用户 ID 和站的 IP(和 winLoc)保存到给定应用程序的数据库或本地用户首选项文件,然后加载该站和应用程序的用户首选项。

Point pBaseLoc = new Point(40, 40)
int x = -500, y = 140;
Point pLoc = new Point(x, y);
bool bIsInsideBounds = false;

foreach (Screen s in Screen.AllScreens)
{
    bIsInsideBounds = s.Bounds.Contains(pLoc);
    if (bIsInsideBounds) { break; }
}//foreach (Screen s in Screen.AllScreens)

if (!bIsInsideBounds) { pLoc = pBaseLoc;  }

this.Location = pLoc;

回答by chris LB

Check:

查看:

SystemInformation.VirtualScreen.Width
SystemInformation.VirtualScreen.Height

回答by JD - DC TECH

You can use the Bounds of System.Drawing.

您可以使用 的边界System.Drawing

You can create a function like this

您可以创建这样的函数

public System.Windows.Form.Screen[] GetScreens(){
    Screen[] screens = Screen.AllScreens;
    return screens;
}

and than you can get the screen one, two, etc. in a variable like this:

然后你可以在这样的变量中获得屏幕一、二等:

System.Windows.Form.Screen[] screens = func.GetScreens();
System.Windows.Form.Screen screen1 = screens[0];

then you can get the bounds of the screen:

然后你可以得到屏幕的边界:

System.Drawing.Rectangle screen1Bounds = screen1.Bounds;

With this code you will get all the properties like Width, Height, etc.

有了这个代码,你会得到像所有属性WidthHeight等等。

回答by dynamichael

This method returns the rectangle that contains all of the screens' bounds by using the lowest values for Left and Top, and the highest values for Right and Bottom...

此方法使用 Left 和 Top 的最低值以及 Right 和 Bottom 的最高值返回包含所有屏幕边界的矩形...

static Rectangle GetDesktopBounds() {
   var l = int.MaxValue;
   var t = int.MaxValue;
   var r = int.MinValue;
   var b = int.MinValue;
   foreach(var screen in Screen.AllScreens) {
      if(screen.Bounds.Left   < l) l = screen.Bounds.Left  ;
      if(screen.Bounds.Top    < t) t = screen.Bounds.Top   ;
      if(screen.Bounds.Right  > r) r = screen.Bounds.Right ;
      if(screen.Bounds.Bottom > b) b = screen.Bounds.Bottom;
   }
   return Rectangle.FromLTRB(l, t, r, b);
}

回答by core.tweaks

I think the best way to get the "real" screen-size, is to get the values directly from the video-controller.

我认为获得“真实”屏幕尺寸的最佳方法是直接从视频控制器获取值。



    using System;
    using System.Management;
    using System.Windows.Forms;

    namespace MOS
    {
        public class ClassMOS
        {
            public static void Main()
            {
                try
                {
                    ManagementObjectSearcher searcher = 
                        new ManagementObjectSearcher("root\CIMV2", 
                        "SELECT * FROM Win32_VideoController"); 

                    foreach (ManagementObject queryObj in searcher.Get())
                    {
                        Console.WriteLine("CurrentHorizontalResolution: {0}", queryObj["CurrentHorizontalResolution"]);
                        Console.WriteLine("-----------------------------------");
                        Console.WriteLine("CurrentVerticalResolution: {0}", queryObj["CurrentVerticalResolution"]);
                    }
                }
                catch (ManagementException e)
                {
                    MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
                }
            }
        }
}


This should do the job ;) Greetings ...

这应该可以完成工作;) 问候...

回答by Andreas

To get the physical pixel size of the monitor you can use this.

要获得显示器的物理像素大小,您可以使用它。

static class DisplayTools
{
    [DllImport("gdi32.dll")]
    static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

    private enum DeviceCap
    {
        Desktopvertres = 117,
        Desktophorzres = 118
    }

    public static Size GetPhysicalDisplaySize()
    {
        Graphics g = Graphics.FromHwnd(IntPtr.Zero);
        IntPtr desktop = g.GetHdc();

        int physicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.Desktopvertres);
        int physicalScreenWidth = GetDeviceCaps(desktop, (int)DeviceCap.Desktophorzres);

        return new Size(physicalScreenWidth, physicalScreenHeight);
    }


}

回答by Konstantin S.

Get the Sizeof 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);
}