我正在开发C#应用程序。每当新的USB驱动器连接到PC时,我都必须触发一个事件。这是我现在的代码:
public class usbState
{
public usbState()
{
}
private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
Console.WriteLine(property.Name + " = " + property.Value);
}
}
private void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
Console.WriteLine(property.Name + " = " + property.Value);
}
}
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
insertWatcher.Start();
WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
removeWatcher.Start();
// Do something while waiting for events
System.Threading.Thread.Sleep(20000000);
}
}
class Program
{
static void Main(string[] args)
{
usbState usb = new usbState();
BackgroundWorker bgwDriveDetector = new BackgroundWorker();
bgwDriveDetector.DoWork += usb.backgroundWorker1_DoWork;
bgwDriveDetector.RunWorkerAsync();
bgwDriveDetector.WorkerReportsProgress = true;
bgwDriveDetector.WorkerSupportsCancellation = true;
// System.Threading.Thread.Sleep(100000);
Console.ReadKey();
}
}
此代码可以正常工作并提供连接的USB的属性,但是问题是它没有提供连接USB的端口。我如何获取连接USB的端口号。
答案 0 :(得分:0)
我使用此方法返回端口的确切名称(COM1,COM2 ...),例如,您应提供设备的预期名称(arduino,Camra ...)以及以ms为单位的搜索超时:
private string GetCOMName(string sExpectedPortName, int iTimeOut)
{
Stopwatch sp = new Stopwatch(); sp.Start();
string sPortName = "Unknown";
bool isPortFound = false;
while (sp.ElapsedMilliseconds < iTimeOut)
{
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
{
var portnames = SerialPort.GetPortNames();
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());
var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();
foreach (var port in portList)
{
// Pass here the expected name of your port , for example (Arduino or Camera...)
if (port.Contains(sExpectedPortName))
{
var start = port.IndexOf("(") + 1;//add one to not include quote
var end = port.LastIndexOf(")") - start;
sPortName = port.Substring(start, end);
isPortFound = true;
break;
}
}
Thread.Sleep(1000);
}
// if the port is found then we go out from the whileloop
if (true == isPortFound)
break;
}
// return the result
return sPortName;
}