本文介绍了我如何获得串行端口的设备ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个节目,我第一次尝试连接到availalbe端口。
如果发现连接,我想读连接的USB设备ID和供应商ID,我该怎么做呢?



亲切的问候

 程序()
{

//获取串行端口名称列表。
的String [] =端口SerialPort.GetPortNames();

//寻找正确的端口。
的foreach(港口串口)
{
_serialPort =新的SerialPort(港,250000 Parity.None,8,StopBits.One);
_serialPort.Handshake = Handshake.None;
_serialPort.ReadTimeout = 300;
_serialPort.WriteTimeout = 300;


{
_serialPort.Open();
中断;
}
赶上(例外五)
{
Console.WriteLine(串口+端口+:+ e.Message);
}
}
/ *输入代码以在这里得到ID * /

Console.WriteLine(使用:+ _serialPort.PortName);
Console.WriteLine(设备ID:+ _serialPort.DeviceID);


解决方案

我终于得到这个整理出自己几天前。有两部分,一是检查注册表,另一个检查设备的VID / PID。



我用只是为了确保我不会在注册表的方法。捕捉空调制解调器模拟器像com0com

  ///<总结> 
///移除所允许的ALLOWED_TYPES
没有明确定义的通信端口///< /总结>
///< PARAM NAME =allPorts>参考列出要检查< /参数>
///<&回报GT;< /回报>
私有静态无效nullModemCheck(参考表<串> allPorts)
{
//打开注册表以获取可用系统
的RegistryKey REGKEY = Registry.LocalMachine的COM端口;
REGKEY = regKey.OpenSubKey(REG_COM_STRING);

&字典LT;字符串,字符串> tempDict =新词典<字符串,字符串>();
的foreach(在allPorts串p)的
tempDict.Add(P,P);

//这个拥有我们可能会发现$ B任何匹配$ B字符串匹配=;
的foreach(在regKey.GetValueNames串子())
{
//名称必须包含VCP或Seial有效。过程中不要匹配
//比较来子项(REGKEY条目名称)
的任何条目,如果(!(subKey.Contains(串行)|| subKey.Contains(VCP)))
{
//好,这可能是一个非法的端口。
//皮克在字典中,我们有如此重要呢?比较regKey.GetValue(子项)
如果(tempDict.TryGetValue(regKey.GetValue(子项)的ToString(),出赛))
{
//杀吧!
allPorts.Remove(比赛);

//重置我们输出字符串
匹配=;
}

}

}

regKey.Close();
}

的VID / PID部分是从的

  ///<总结> 
///编译给定的VID和PID
///及相关联的COM端口的名称数组; /总结>
///< PARAM NAME =VID>字符串代表USB /串口转换器<的供应商ID; /参数>
///< PARAM NAME =PID>表示USB /串口转换器<的产品ID字符串; /参数>
///<&回报GT;< /回报>
私人静态列表<串GT; getPortByVPid(VID字符串,字符串PID)
{
字符串模式=的String.Format(^ VID_ {0} .PID_ {1},VID,PID);
正则表达式_rx =新的正则表达式(模式,RegexOptions.IgnoreCase);
名单,LT;字符串>相称=新的List<串GT;();
的RegistryKey RK1 = Registry.LocalMachine;
的RegistryKey RK 2 = rk1.OpenSubKey(SYSTEM\\CurrentControlSet\\Enum);
的foreach(字符串中rk2.GetSubKeyNames S3())
{
的RegistryKey RK3 = rk2.OpenSubKey(S3);
的foreach(字符串S IN rk3.GetSubKeyNames())
{
如果(_rx.Match(S).Success)
{
的RegistryKey RK4 = rk3.OpenSubKey (多个);
的foreach(字符串中rk4.GetSubKeyNames S2())
{
的RegistryKey RK5 = rk4.OpenSubKey(S2);
的RegistryKey rk6 = rk5.OpenSubKey(设备参数);
comports.Add((字符串)rk6.GetValue(端口名称));
}
}
}
}
回报相称;
}


In this program I'm first trying to connect to availalbe port.When found and connected, I want to read the connected USB device ID and vendor ID, How do I do that?

Kind Regards

Program()
    {

        // Get a list of serial port names.
        string[] ports = SerialPort.GetPortNames();

        // Search for the right port.
        foreach (string port in ports)
        {
            _serialPort = new SerialPort(port, 250000, Parity.None, 8, StopBits.One);
            _serialPort.Handshake = Handshake.None;
            _serialPort.ReadTimeout = 300;
            _serialPort.WriteTimeout = 300;

            try
            {
                _serialPort.Open();
                break;
            }
            catch (Exception e)
            {
                Console.WriteLine("Serial port " + port + ": " + e.Message);
            }
        }
        /* ENTER CODE TO GET ID HERE */

        Console.WriteLine("Using: " + _serialPort.PortName);
        Console.WriteLine("Device ID: " + _serialPort.DeviceID);
解决方案

I finally got this sorted out myself a couple days ago. There are two parts, one to check the registry and another to check the vid/pid of the device.

The registry method I use just to make sure I don't capture a null modem emulator like com0com.

        /// <summary>
    /// Removes any comm ports that are not explicitly defined as allowed in ALLOWED_TYPES
    /// </summary>
    /// <param name="allPorts">reference to List that will be checked</param>
    /// <returns></returns>
    private static void nullModemCheck(ref List<string> allPorts)
    {
        // Open registry to get the COM Ports available with the system
        RegistryKey regKey = Registry.LocalMachine;
        regKey = regKey.OpenSubKey(REG_COM_STRING);

        Dictionary<string, string> tempDict = new Dictionary<string, string>();
        foreach (string p in allPorts)
            tempDict.Add(p, p);

        // This holds any matches we may find
        string match = "";
        foreach (string subKey in regKey.GetValueNames())
        {
            // Name must contain either VCP or Seial to be valid. Process any entries NOT matching
            // Compare to subKey (name of RegKey entry)
            if (!(subKey.Contains("Serial") || subKey.Contains("VCP")))
            {
                // Okay, this might be an illegal port.
                // Peek in the dictionary, do we have this key? Compare to regKey.GetValue(subKey)
                if(tempDict.TryGetValue(regKey.GetValue(subKey).ToString(), out match))
                {
                    // Kill it!
                    allPorts.Remove(match);

                    // Reset our output string
                    match = "";
                }

            }

        }

        regKey.Close();
    }

The vid/pid portion was gleaned from techinpro

    /// <summary>
    /// Compile an array of COM port names associated with given VID and PID
    /// </summary>
    /// <param name="VID">string representing the vendor id of the USB/Serial convertor</param>
    /// <param name="PID">string representing the product id of the USB/Serial convertor</param>
    /// <returns></returns>
    private static List<string> getPortByVPid(String VID, String PID)
    {
        String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID);
        Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
        List<string> comports = new List<string>();
        RegistryKey rk1 = Registry.LocalMachine;
        RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");
        foreach (String s3 in rk2.GetSubKeyNames())
        {
            RegistryKey rk3 = rk2.OpenSubKey(s3);
            foreach (String s in rk3.GetSubKeyNames())
            {
                if (_rx.Match(s).Success)
                {
                    RegistryKey rk4 = rk3.OpenSubKey(s);
                    foreach (String s2 in rk4.GetSubKeyNames())
                    {
                        RegistryKey rk5 = rk4.OpenSubKey(s2);
                        RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
                        comports.Add((string)rk6.GetValue("PortName"));
                    }
                }
            }
        }
        return comports;
    }

这篇关于我如何获得串行端口的设备ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:55