IT TIP

C # : 전체 데스크톱 크기를 얻으시겠습니까?

itqueen 2020. 10. 20. 18:58
반응형

C # : 전체 데스크톱 크기를 얻으시겠습니까?


전체 데스크탑의 크기는 어떻게 알 수 있습니까? 아니 은 "작업 영역"과 하지 오직 하나의 화면을 참조 둘의 "화면 해상도". 각 모니터에 일부만 표시되는 가상 데스크톱의 전체 너비와 높이를 알고 싶습니다.


두 가지 옵션이 있습니다.

  1. PresentationFramework.dll

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

    SystemInformation.VirtualScreen.Width   
    SystemInformation.VirtualScreen.Height
    

WPF 애플리케이션을 개발하는 경우 첫 번째 옵션을 사용하십시오 .


이제는 약간의 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);

검사:

SystemInformation.VirtualScreen.Width
SystemInformation.VirtualScreen.Height

이것은 질문에 답하는 것이 아니라 모든 화면 내 창의 지점 (위치)에 대한 추가 통찰력을 추가 할뿐입니다.

아래 코드를 사용하여 포인트 (예 : 마지막으로 알려진 창의 위치)가 전체 데스크탑 경계 내에 있는지 확인하십시오. 그렇지 않은 경우 창 위치를 기본 pBaseLoc 로 재설정하십시오 .

코드는 작업 표시 줄이나 다른 도구 모음을 고려하지 않습니다.

사용 예 : 스테이션 A 에서 데이터베이스에 창 위치를 저장합니다 . 사용자 는 2 대의 모니터 스테이션 B에 로그인 하고 창을 두 번째 모니터로 이동하고 로그 아웃하여 새 위치를 저장합니다. 역 A로 돌아 가면 위의 코드를 사용하지 않는 한 창이 표시되지 않습니다.

내 추가 해결 방법은 사용자 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;

모니터의 실제 픽셀 크기를 얻으려면 이것을 사용할 수 있습니다.

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


}

의 경계를 사용할 수 있습니다 System.Drawing.

다음과 같은 함수를 만들 수 있습니다.

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

다음과 같은 변수에서 화면 1, 2 등을 얻을 수 있습니다.

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

그러면 화면의 경계를 얻을 수 있습니다.

System.Drawing.Rectangle screen1Bounds = screen1.Bounds;

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


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 ...


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...

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

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

참고URL : https://stackoverflow.com/questions/1317235/c-get-complete-desktop-size

반응형