【问题标题】:list all connected devices on windows列出 Windows 上所有连接的设备
【发布时间】:2017-11-21 12:49:40
【问题描述】:

如何使用 c# 获取所有连接的设备,例如在 Control Panel\Hardware and Sound\Devices and Printers 中?

【问题讨论】:

    标签: c# windows controlpanel input-devices


    【解决方案1】:

    尝试在您的项目中添加对 System.Management 的引用,然后您可以进行如下实验:

    namespace ConsoleApplication1 {
        using System;
        using System.Collections.Generic;
        using System.Management; // need to add System.Management to your project references.
    
        class Program {
            static void Main(string[] args) {
                var usbDevices = GetUSBDevices();
    
                foreach(var usbDevice in usbDevices) {
                    Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}", usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
                }
    
                Console.Read();
            }
    
            static List < USBDeviceInfo > GetUSBDevices() {
                List < USBDeviceInfo > devices = new List < USBDeviceInfo > ();
    
                ManagementObjectCollection collection;
                using(var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
                collection = searcher.Get();
    
                foreach(var device in collection) {
                    devices.Add(new USBDeviceInfo((string) device.GetPropertyValue("DeviceID"), (string) device.GetPropertyValue("PNPDeviceID"), (string) device.GetPropertyValue("Description")));
                }
    
                collection.Dispose();
                return devices;
            }
        }
    
        class USBDeviceInfo {
            public USBDeviceInfo(string deviceID, string pnpDeviceID, string description) {
                this.DeviceID = deviceID;
                this.PnpDeviceID = pnpDeviceID;
                this.Description = description;
            }
            public string DeviceID {
                get;
                private set;
            }
            public string PnpDeviceID {
                get;
                private set;
            }
            public string Description {
                get;
                private set;
            }
        }
    }
    

    编辑:友好名称

    ManagementObjectCollection mbsList = null;
                ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select * From Win32_USBHub");
                mbsList = mbs.Get();
    
                foreach (ManagementObject mo in mbsList)
                {
                    Console.WriteLine("USBHub device Friendly name:{0}", mo["Name"].ToString());
                }
    

    【讨论】:

    • 谢谢。这部分有效,我怎样才能获得控制面板中指定的型号名称?
    • 型号?就像设备的型号一样?
    • 我试过了,不幸的是输出与控制面板中的显示不同,知道如何获取显示名称吗?
    猜你喜欢
    • 2018-05-16
    • 2017-12-25
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 2013-11-26
    • 1970-01-01
    相关资源
    最近更新 更多