C# 实时轮询通用串行总线设备列表
需要安装System.Management。
1.背景需求:
实时获取通用串行总线设备列表,设置时间轮询机制(5s)
2.上述代码
using System;
using System.Management;
using System.Timers;
class Program
{
private static Timer timer;
static void Main(string[] args)
{
// 设置定时器,每5000毫秒(5秒)触发一次Elapsed事件
timer = new Timer(5000);
timer.Elapsed += TimerElapsed;
timer.AutoReset = true; // 设置为true以使定时器在每次触发后自动重置
timer.Enabled = true; // 启动定时器
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
// 停止并释放定时器资源
timer.Stop();
timer.Dispose();
}
private static void TimerElapsed(Object source, ElapsedEventArgs e)
{
//在这里执行WMI查询
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE PNPDeviceID LIKE 'USB%'");
foreach (ManagementObject device in searcher.Get())
{
// 注意:这里仅输出到控制台,如果你需要在其他线程中更新UI,请使用适当的线程同步机制
Console.WriteLine("Device ID: " + device["DeviceID"]);
Console.WriteLine("PNP Device ID: " + device["PNPDeviceID"]);
Console.WriteLine("Description: " + device["Description"]);
// ... 其他你感兴趣的属性
Console.WriteLine();
}
}
catch (ManagementException ex)
{
// 处理WMI查询异常
Console.WriteLine("WMI query failed: " + ex.Message);
}
}
}
4.运行截图:
4.背景需求:
实时获取通用串行总线设备列表,设置时间轮询机制(5s),然后根据已知的VID(VID 3068)和PID(PID 0009),去打印相应的USB设备信息。此需求是去索引周立功CANFD200U设备信息。
5. 上述代码
using System;
using System.Management;
using System.Timers;
class Program
{
private static Timer timer;
static void Main(string[] args)
{
// 设置定时器,每5000毫秒(5秒)触发一次Elapsed事件
timer = new Timer(5000);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true; // 设置为true以使定时器在每次触发后自动重置
timer.Enabled = true; // 启动定时器
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
// 停止并释放定时器资源
timer.Stop();
timer.Dispose();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
try
{
// 查询所有USB设备
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE PNPDeviceID LIKE 'USB%'");
string query = "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{36FC9E60-C465-11CF-8056-444553540000}\"";
//using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
//{
foreach (ManagementObject device in searcher.Get())
{
// 获取PNPDeviceID属性
string pnpDeviceID = (string)device["PNPDeviceID"];
// 检查PNPDeviceID是否包含指定的VID和PID [以周立功CANFD200U为例]
if (pnpDeviceID != null && pnpDeviceID.Contains("VID_3068") && pnpDeviceID.Contains("PID_0009"))
{
// 输出设备信息
Console.WriteLine("Device ID: " + (string)device["DeviceID"]);
Console.WriteLine("PNP Device ID: " + pnpDeviceID);
Console.WriteLine("Description: " + (string)device["Description"]);
Console.WriteLine();
}
}
// 如果循环中没有找到任何设备,则不需要额外的检查,因为已经检查了所有设备
// }
Console.WriteLine("__________________________");
}
catch (ManagementException ex)
{
// 处理WMI查询异常
Console.WriteLine("WMI query failed: " + ex.Message);
}
}
}