Skip to content

Instantly share code, notes, and snippets.

@grandsilence
Last active November 14, 2018 18:02
Show Gist options
  • Save grandsilence/cd7ce9d8bf87a5414b685e3e32542dd3 to your computer and use it in GitHub Desktop.
Save grandsilence/cd7ce9d8bf87a5414b685e3e32542dd3 to your computer and use it in GitHub Desktop.
C# Получение модели монитора
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
namespace ConsoleApp1
{
public static class MonitorsInfo
{
public static string UnknownMonitor => "Неопознанный монитор"; // Тут можешь вызывать функцию локализации
public static string[] GetMergedFriendlyNames()
{
var namesByMonitorIds = GetNamesByMonitorIds();
var captions = GetCaptions();
if (namesByMonitorIds.Length == 0)
return captions;
if (captions.Length == 0 || namesByMonitorIds.Length != captions.Length)
return namesByMonitorIds;
return namesByMonitorIds.Select((nameByMonitorId, i) => captions[i] == UnknownMonitor ? nameByMonitorId : captions[i]).ToArray();
}
public static string[] GetNamesByMonitorIds()
{
var result = new List<string>();
ManagementObjectSearcher searcher = null;
ManagementObjectCollection monitors = null;
try
{
var scope = new ManagementScope("\\\\.\\ROOT\\WMI");
var query = new ObjectQuery("SELECT * FROM WmiMonitorID");
searcher = new ManagementObjectSearcher(scope, query);
monitors = searcher.Get();
if (monitors.Count > 0)
{
foreach (var monitor in monitors)
{
string userFriendlyName = monitor["UserFriendlyName"].AsString();
result.Add(!string.IsNullOrEmpty(userFriendlyName) && !userFriendlyName.Contains("PnP") ? userFriendlyName : UnknownMonitor);
}
}
}
catch (Exception)
{
// ignored
}
finally
{
// Не мусорим в памяти
monitors?.Dispose();
searcher?.Dispose();
}
return result.ToArray();
}
private static string[] GetCaptions()
{
var result = new List<string>();
ManagementObjectSearcher searcher = null;
ManagementObjectCollection monitors = null;
try
{
searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
monitors = searcher.Get();
if (monitors.Count > 0)
{
foreach (var monitor in monitors)
{
string caption = monitor["Caption"]?.ToString().Trim();
result.Add(!string.IsNullOrEmpty(caption) && !caption.Contains("PnP") ? caption : UnknownMonitor);
}
}
}
catch (Exception)
{
// ignored
}
finally
{
monitors?.Dispose();
searcher?.Dispose();
}
return result.ToArray();
}
private static string AsString(this object obj)
{
switch (obj) {
case null:
case IReadOnlyList<ushort> decArray when decArray.Count == 0 || decArray[0] == 0:
return string.Empty;
case IReadOnlyList<ushort> decArray: {
var sb = new StringBuilder();
foreach (ushort val in decArray)
{
if (val == 0)
break;
// ASCII codes only (escape)
if (val >= 32 && val <= 127)
sb.Append((char)val);
}
return sb.ToString().Trim();
}
default:
return string.Empty;
}
}
}
}
using System;
namespace ConsoleApp1
{
internal class Program
{
private static void Main(string[] args)
{
// Использовать только один из вариантов.
// Предпочтительнее первый, т.к. он универсальный и пробует получать заголовки мониторов.
// Способ №1
// Получаем или caption (если не Universal Plug & Play устройство) или просто производитель + модель (PowerShell скрипт)
var monitors = MonitorsInfo.GetMergedFriendlyNames();
foreach (var monitor in monitors)
Console.WriteLine(monitor);
// Способ №2
var monitorsByMonitorIds = MonitorsInfo.GetNamesByMonitorIds();
foreach (var monitorByMonitorId in monitorsByMonitorIds)
Console.WriteLine(monitorByMonitorId);
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment