简体   繁体   English

检测显示器数量

[英]Detect number of display monitor

I already tried Screen.AllScreen, SystemInformation.MonitorCount, and WMI but all of them failed. 我已经尝试过Screen.AllScreen,SystemInformation.MonitorCount和WMI,但它们都失败了。

My application runs as a windows service, hence no visual Form or UI. 我的应用程序作为Windows服务运行,因此没有可视的Form或UI。 Both Screen.AllScreen and SystemInformation.MonitorCount returns 1 even when I have 2 monitors. 即使我有2个监视器,Screen.AllScreen和SystemInformation.MonitorCount都返回1。 If I run my application in console, it returns the correct count of display but my requirement is that my application to run as a windows service (no UI). 如果我在控制台中运行应用程序,它将返回正确的显示计数,但是我的要求是我的应用程序必须以Windows服务(无UI)运行。

Thanks! 谢谢!

Found answer to my own question. 找到了我自己的问题的答案。 Still end up using WMI. 仍然最终使用WMI。

I was initially using Win32_DesktopMonitor giving a non-reliable answer. 我最初使用Win32_DesktopMonitor给出了不可靠的答案。

Using this query: 使用此查询:

"SELECT * FROM Win32_PnPEntity WHERE Service = 'monitor'"

WMI returns the correct monitor instance connected to my PC. WMI返回连接到我的PC的正确监视器实例。

I went with Win32_PnPEntity because it represents the information for Plug and Play Devices in your Device Manager, which will show you when you have a monitors plugged in. The way the query works in "searcher" is more likely to be accurate than others since it uses the Like Operator. 我使用Win32_PnPEntity是因为它表示设备管理器中即插即用设备的信息,当您插入监视器时,它将向您显示。查询在“搜索器”中的工作方式比其他方式更准确,因为使用Like运算符。 I do this because on 3 different computers the monitor entries in Device manager appeared differently. 我这样做是因为在3台不同的计算机上,设备管理器中的监视器条目出现的方式有所不同。 Eg (Pnp-Monitor, Pnp Monitor (Standard), Generic Pnp Monitor). 例如(即插即用监视器,即插即用监视器(标准),通用即插即用监视器)。

private int CountMonitorsInstalled()
{
    try
    {
     ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "select * from Win32_PnPEntity WHERE Name LIKE '%PnP%Monitor%'");
     return searcher.Get().Count;
    }
    catch(Exception ex)
    {
      return 0;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM