【问题标题】:Identifying USB to serial port given USB VID and PID using WMI query使用 WMI 查询在给定 USB VID 和 PID 的情况下识别 USB 到串行端口
【发布时间】:2014-05-12 14:45:43
【问题描述】:

我正在使用 WMI 查询来检测 USB 到串行端口,但问题是在 windows 7 中,应用程序需要很长时间才能启动,而在 windows xp 中它工作正常。我正在通过以下方式使用 wmi 查询

ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPDevice");
            foreach (ManagementObject queryObj in searcher.Get())
            {
                if (queryObj["SameElement"].ToString().Contains("SerialPort"))
                {
                    //do something
                 }
             }

根据我的推理,这是由于大量 Pnp 设备和从该列表中查询串行端口而发生的。我尝试使用 Win32_SerialPort,但它在我的笔记本电脑(windows 7)上在 windows xp 中工作,即使它们是虚拟串行端口和 USB 到串行端口,它也会显示不支持的消息。即使从管理员帐户也不起作用。 MSSerial_PortName 在我的笔记本电脑(windows7)上也不起作用。因此,他们有什么方法可以让我的应用程序在 Windows 7 中使用 WMI 查询更快地启动?

【问题讨论】:

    标签: c# wmi-query usbserial


    【解决方案1】:

    Win32_PnPDevice 需要很长时间 MSSerial_PortName 适用于我的 Win 7 笔记本电脑。 试试这个(应该可以,从我的程序修改):

    try
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName");
            foreach (ManagementObject queryObj in searcher.Get())
            {
                serialPort = new SerialPort(queryObj["PortName"].ToString(), 115200, Parity.None, 8, StopBits.One);//change parameters
                //If the serial port's instance name contains USB
                //it must be a USB to serial device
                if (queryObj["InstanceName"].ToString().Contains("USB"))//if you have a VID or PID name then this should not be nessesery
                {
                    //should get serial to usb adapters
                    try
                    {
                        serialPort.Open();
                        if (queryObj["InstanceName"].ToString().Contains(VID_or_PID))
                        {
                            //do sth
                        }
                        serialPort.Close();
                    }
                    catch (Exception ex)
                    {
                        //exception handling
                    }
                }
    
            }
        }
        catch (ManagementException ex)
        {
            //write("Querying for WMI data. Exception raised(" + ex.Message + "): " + ex);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多