如何在c#中找到USB设备?
发布时间:2020-12-15 04:13:32 所属栏目:百科 来源:网络整理
导读:我需要遍历连接到计算机的端口,并找到特定的设备.请看下面的图片: 您可以看到有4个设备名称具有相同的供应商和产品ID.但是,我需要找到第一个的端口,它以蓝色突出显示.看起来他们唯一的区别就是朋友的名字(描述是朋友的名字). 在C#.net中实现这一目标的最简
我需要遍历连接到计算机的端口,并找到特定的设备.请看下面的图片:
您可以看到有4个设备名称具有相同的供应商和产品ID.但是,我需要找到第一个的端口,它以蓝色突出显示.看起来他们唯一的区别就是朋友的名字(描述是朋友的名字). 在C#.net中实现这一目标的最简单方法是什么?我在’qt’中完成了这个,我需要知道如何使用vs 2010 professional在C#,.net framework 4中完成此操作.我已经经历了像this这样的问题,但正如你所看到的,他们对我的情况毫无帮助. 解决方法
如果您使用
libusbdotnet,您应该能够做到这样的事情:
public static void RetrieveUSBDevices(int vid,int pid) { var usbFinder = new UsbDeviceFinder(vid,pid); var usbDevices = new UsbRegDeviceList(); usbDevices = usbDevices.FindAll(usbFinder); } 然后你应该能够迭代usbDevices并检查正确的FullName.虽然没有测试,但它是理论上的. 更新: 这也有效: private static void Method() { var list = GetMyUSBDevices(); //Iterate list here and use Description to find exact device } private static List<UsbDevice> GetMyUSBDevices() { var vid = 32903; var pid = 36; ManagementObjectCollection collection; using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub")) collection = searcher.Get(); var usbDevice = (from ManagementBaSEObject device in collection select new UsbDevice( (string) device.GetPropertyValue("DeviceID"),(string) device.GetPropertyValue("Description"))).ToList(); var devices = new List<UsbDevice>(); foreach (var device in collection) { devices.Add(new UsbDevice( (string)device.GetPropertyValue("DeviceID"),(string)device.GetPropertyValue("Description") )); } collection.Dispose(); return (from d in devices where d.DeviceId.Contains("VID_") && d.DeviceId.Contains("PID_") && d.PID.Equals(pid) && d.VID.Equals(vid) select d).ToList(); } public class UsbDevice { public UsbDevice(string deviceId,string description) { DeviceId = deviceId; Description = description; } public string DeviceId { get; private set; } public string Description { get; private set; } public int VID { get { return int.Parse(GetIdentifierPart("VID_"),System.Globalization.NumberStyles.HexNumber); } } public int PID { get { return int.Parse(GetIdentifierPart("PID_"),System.Globalization.NumberStyles.HexNumber); } } private string GetIdentifierPart(string identifier) { var vidIndex = DeviceId.IndexOf(identifier,StringComparison.Ordinal); var startingAtVid = DeviceId.Substring(vidIndex + 4); return startingAtVid.Substring(0,4); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |