C#: Obtener el tamaño completo del escritorio?


¿Cómo puedo averiguar el tamaño de todo el escritorio? Noel "área de trabajo" y no la "resolución de pantalla", ambos se refieren a una sola pantalla. Quiero averiguar el ancho y la altura total del escritorio virtual del que cada monitor muestra solo una parte.

Author: Roman Starkov, 2009-08-23

8 answers

Tienes dos opciones:

  1. PresentationFramework.dll

    SystemParameters.VirtualScreenWidth   
    SystemParameters.VirtualScreenHeight
    
  2. Sistema.Windows.Forma.dll

    SystemInformation.VirtualScreen.Width   
    SystemInformation.VirtualScreen.Height
    

Utilice la primera opción si está desarrollando una aplicación WPF.

 122
Author: Dennis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-08 17:53:24

Creo que es hora de actualizar esta respuesta con un poco de LINQ, lo que facilita obtener todo el tamaño del escritorio con una sola expresión.

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

Mi respuesta original sigue:


, supongo que lo que quieres es algo como esto:

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);

Tenga en cuenta que esto no cuenta toda la historia. Es posible que varios monitores estén escalonados o dispuestos en una forma no rectangular. Por lo tanto, puede ser que no todo el espacio entre (minx, miny) y (maxx, maxy) es visible.

EDITAR:

Acabo de darme cuenta de que el código podría ser un poco más simple usando 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);
 27
Author: P Daddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-27 02:29:09

Compruebe:

SystemInformation.VirtualScreen.Width
SystemInformation.VirtualScreen.Height
 15
Author: chris LB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-25 19:02:23

Para obtener el tamaño de píxel físico del monitor puede usar esto.

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);
    }


}
 6
Author: Andreas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-27 11:28:31

Esto no responde a la pregunta, sino que simplemente agrega información adicional sobre el Punto (ubicación) de una ventana dentro de todas las pantallas).

Use el siguiente código para averiguar si un Punto (por ejemplo, la última ubicación conocida de window) está dentro de los límites del Escritorio general. Si no, restablezca la ubicación de la ventana a la predeterminada pBaseLoc ;

El código no tiene en cuenta la barra de tareas u otras barras de herramientas, yer on yer own allí.

Ejemplo de uso: Guardar la ubicación de la ventana en una base de datos desde estación A . El usuario inicia sesión en station B con 2 monitores y mueve la ventana al 2do monitor, cierra la sesión guardando una nueva ubicación. Volver a estación A y la ventana no se mostrará a menos que se utilice el código anterior.

Mi resolución adicional implementó guardar el ID de usuario y la IP de la estación (& winLoc) en la base de datos o en el archivo de prefs del usuario local para una aplicación determinada, luego cargar el preff del usuario para esa estación y aplicación.

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;
 5
Author: TechStuffBC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-06 00:24:46

Puedes usar los Límites de System.Drawing.

Puede crear una función como esta

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

Y entonces usted puede conseguir la pantalla uno, dos, etc. en una variable como esta:

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

Entonces puedes obtener los límites de la pantalla:

System.Drawing.Rectangle screen1Bounds = screen1.Bounds;

Con este código obtendrá todas las propiedades como Width, Height, etc.

 0
Author: JD - DC TECH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-19 09:51:00

Creo que la mejor manera de obtener el tamaño de pantalla "real", es obtener los valores directamente del controlador de video.


    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);
                }
            }
        }
}

Esto debería hacer el trabajo ;) Saludo ...

 0
Author: core.tweaks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-10 20:10:19

Este método devuelve el rectángulo que contiene todos los límites de las pantallas utilizando los valores más bajos para la Izquierda y la Parte superior, y los valores más altos para la Derecha y la Parte Inferior...

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);
}
 0
Author: dynamichael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-14 02:44:10