I am working on a C# application. I have to trigger an event whenever a new USB drive is connected to the PC. This is my code for now:
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();
}
}
This code works fine and gives the properties of the attached USB, but issue is that it does not give the PORT on which USB is connected. How can i get the port number on which we have attached the USB.
i use this method to return the exact name of the port (COM1, COM2...), you should provide the expected name of the device for example (arduino, Camra...) and a search time out in 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.