如何在 C# 中获取连接到 PC 的显示器的数量?

Dom*_*alo 2 c# wpf screen

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

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

Sim*_*rle 6

请尝试以下操作:

    System.Management.ManagementObjectSearcher monitorObjectSearch = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
    int Counter = monitorObjectSearch.Get().Count;
Run Code Online (Sandbox Code Playgroud)

在以下问题中找到了答案:

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;
    }
Run Code Online (Sandbox Code Playgroud)

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

也许您还需要增加其他状态码的计数器。查看链接以获取更多信息。