简体   繁体   English

获取C#中新连接的USB设备的COM端口(串口)

[英]Get COM port (Serial Port) of newly connected USB device in C#

I am working on a C# application.我正在开发 C# 应用程序。 I have to trigger an event whenever a new USB drive is connected to the PC.每当新的 USB 驱动器连接到 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.此代码工作正常,并给出了附加的 USB 的属性,但问题是它没有给出连接 USB 的端口。 How can i get the port number on which we have attached the USB.我怎样才能获得我们附加了 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:我使用此方法返回端口的确切名称(COM1、COM2...),您应该提供设备的预期名称,例如(arduino、Camra...)和以毫秒为单位的搜索超时:

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM