This is a fairly technical post explaining how I managed to get C# to show the number of physical monitors connected to a PC.
My problem was that when connected through VNC or Remote Desktop (or even when I wasn’t) our computers were still reporting that they had a resolution and a default monitor.
After trying fairly standard code such as
Screen [] screens = Screen.AllScreens;
Source
Or even WMI queries such as
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DesktopMonitor");
Source
All these queries returned that a monitor, normally Default Display, was connected to the computer. As students occasionally unplug a monitor to dual display a second PC I needed be able to programmatically confirm that the screen is actually connected.
In the end, and I’m writing this down so that anyone else in my situation can find it through Google, the following code worked (thanks to rix0rrr)
try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity where service=\"monitor\""); int numberOfMonitors = searcher.Get().Count; Console.WriteLine("Number of Monitors = " + numberOfMonitors); } catch (ManagementException e) { MessageBox.Show("An error occurred while querying for WMI data: " + e.Message); }
You’ll need to remember to have using System.Management;
and add a new reference to System.Management before ManagementObjectSearcher will work correctly.
Goose
December 4, 2014 @ 11:34 am
Hi,
when i use the above code, it is showing as invalid query. please can you help me ?
Narada Rathnasooriya
June 6, 2016 @ 10:45 am
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(“root\\CIMV2”,
“SELECT * FROM Win32_PnPEntity where service=”monitor””);
please replace above acode by this,
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(“root\\CIMV2”,
“SELECT * FROM Win32_PnPEntity where service=\”monitor\””);
It’s worked
Graham Robinson
June 6, 2016 @ 11:13 am
Thank you for your comment. Weirdly that is exactly what is in WordPress, but for some reason the theme (or WordPress itself) seems to have removed the backslashes until I turned them into double backslashes.
I wouldn’t have ever spotted this without your help, so thank you again.
Graham
tbhdw
October 31, 2018 @ 9:35 am
Could someone put in here the final code? Cause im not understanding everything.. I have done it until now with de Screen.AllScreen mehtode without result
Detecting number of monitors and their characteristics – A developer's blog
April 1, 2021 @ 6:14 am
[…] https://blog.soton.ac.uk/mle/2013/06/14/determining-the-number-of-monitors/ […]