如何在C#中获得连接到PC的监视器的计数

本文关键字:PC 监视器 连接 | 更新日期: 2023-09-27 17:59:30

我需要检测物理连接到计算机的监视器的数量(以决定屏幕配置是否处于单一、扩展、重复模式)。System.Windows.Forms.Screen.AllScreens.LengthSystem.Windows.Forms.SystemInformation.MonitorCount都返回虚拟屏幕(桌面)的计数。

因此,如果有2个以上的显示器连接到电脑,我可以使用此值在复制/扩展模式之间做出决定,但我无法决定是否只有一个物理显示器连接到PC,因此屏幕配置处于单屏幕模式。

如何在C#中获得连接到PC的监视器的计数

尝试以下操作:

    System.Management.ManagementObjectSearcher monitorObjectSearch = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
    int Counter = monitorObjectSearch.Get().Count;

以下问题的答案:

WMI获取所有监视器未返回所有监视器

更新

尝试以下功能,它检测拔下显示器:

    private int GetActiveMonitors()
    {
        int Counter = 0;
        System.Management.ManagementObjectSearcher monitorObjectSearch = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
        foreach (ManagementObject Monitor in monitorObjectSearch.Get())
        {
            UInt16 Status = 0;
            try
            {
                Status = (UInt16)Monitor["Availability"];
            }
            catch (Exception ex)
            {
                //Error handling if you want to
                continue;
            }
            if (Status == 3)
                Counter++;
        }
        return Counter;
    }

以下是状态列表:https://msdn.microsoft.com/en-us/library/aa394122%28v=vs.85%29.aspx

也许你也需要增加其他雕像的计数器。有关详细信息,请查看链接。

基于Xanatos的答案,我创建了一个简单的助手类来检测屏幕配置:

using System;
using System.Management;
using System.Windows.Forms;
public static class ScreensConfigurationDetector
{
    public static ScreensConfiguration GetConfiguration()
    {
        int physicalMonitors = GetActiveMonitors();
        int virtualMonitors = Screen.AllScreens.Length;
        if (physicalMonitors == 1)
        {
            return ScreensConfiguration.Single;
        }
        return physicalMonitors == virtualMonitors 
            ? ScreensConfiguration.Extended 
            : ScreensConfiguration.DuplicateOrShowOnlyOne;
    }
    private static int GetActiveMonitors()
    {
        int counter = 0;
        ManagementObjectSearcher monitorObjectSearch = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
        foreach (ManagementObject Monitor in monitorObjectSearch.Get())
        {
            try
            {
                if ((UInt16)Monitor["Availability"] == 3)
                {
                    counter++;
                }
            }
            catch (Exception)
            {
                continue;
            }
        }
        return counter;
    }
}
public enum ScreensConfiguration
{
    Single,
    Extended,
    DuplicateOrShowOnlyOne
}

"从Win32_DesktopMonitor中选择*;在Vista之后,查询可能无法正常工作。我花了几个小时寻找解决方案,但没有一个能在Windows7及更新版本中正确处理这个问题。根据多米尼克的回答;

ManagementObjectSearcher searcher = new ManagementObjectSearcher("root''CIMV2", "SELECT * FROM Win32_PnPEntity where service='"monitor'"");
int numberOfMonitors = searcher.Get().Count;

将返回物理监视器的计数。有了这个改变,他的助手类也为我工作了。

我发现在WPF中获取监视器计数的最可靠方法是侦听WM_DISPLAYCHANGE,以了解mionitors何时连接和断开,然后使用EnumDisplayMonitors获取监视器计数。这是代码。

钩住WM_DISPLAYCHANGE消息的WndProc

public partial class MainWindow : IDisposable
{
...
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
            source.AddHook(WndProc);
        }
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_DISPLAYCHANGE)
            {
                int lparamInt = lParam.ToInt32();
                uint width = (uint)(lparamInt & 0xffff);
                uint height = (uint)(lparamInt >> 16);
                int monCount = ScreenInformation.GetMonitorCount();
                int winFormsMonCount = System.Windows.Forms.Screen.AllScreens.Length;
                _viewModel.MonitorCountChanged(monCount);
            }
            return IntPtr.Zero;
        }

获取显示计数

public class ScreenInformation
{
    [StructLayout(LayoutKind.Sequential)]
    private struct ScreenRect
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }
    [DllImport("user32")]
    private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lpRect, MonitorEnumProc callback, int dwData);
    private delegate bool MonitorEnumProc(IntPtr hDesktop, IntPtr hdc, ref ScreenRect pRect, int dwData);
    public static int GetMonitorCount()
    {
        int monCount = 0;
        MonitorEnumProc callback = (IntPtr hDesktop, IntPtr hdc, ref ScreenRect prect, int d) => ++monCount > 0;
        if (EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, callback, 0))
            Console.WriteLine("You have {0} monitors", monCount);
        else
            Console.WriteLine("An error occured while enumerating monitors");
        return monCount;
    }
}