C#获取串口完整名字、并实时监听串口插拔

  1,首先利用System.Management里面提供的类(第一次可能需要添加对System.Management的引用,否则找不到类),获取串口完整名字

2,监听窗口USB插拔事件并更新下拉列表中的串口

        /// <summary>
        /// 获取串口完整名字(包括驱动名字)
        /// 如果找不到类,需要添加System.Management引用,添加引用->程序集->System.Management
        /// </summary>
       Dictionary<String, String> coms = new Dictionary<String, String>();
        private void getPortDeviceName()
        {
            
            coms.Clear();
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher
            ("select * from Win32_PnPEntity where Name like '%(COM%'"))
            {
                var hardInfos = searcher.Get();
                foreach (var hardInfo in hardInfos)
                {
                    if (hardInfo.Properties["Name"].Value != null)
                    {
                        string deviceName = hardInfo.Properties["Name"].Value.ToString();
                        int startIndex = deviceName.IndexOf("(");
                        int endIndex = deviceName.IndexOf(")");
                        string key = deviceName.Substring(startIndex + 1, deviceName.Length - startIndex - 2);
                        string name = deviceName.Substring(0, startIndex - 1);
                        Console.WriteLine("key:"+key+",name:"+name+",deviceName:"+deviceName);
                        coms.Add(key,name);
                    }
                }

                //创建一个用来更新UI的委托 (主线程更新)
                this.Invoke(
                     new Action(() =>   
                     {
                         comboBox1.Items.Clear();
                         foreach (KeyValuePair<string, string> kvp in coms)
                         {    
                             comboBox1.Items.Add(kvp.Key + " " + kvp.Value);//更新下拉列表中的串口
                         }

                     })
                 );
      
            }
            
        }

        public const int WM_DEVICE_CHANGE = 0x219;
        public const int DBT_DEVICEARRIVAL = 0x8000;
        public const int DBT_DEVICE_REMOVE_COMPLETE = 0x8004;
        /// <summary>
        /// 检测USB串口的拔插
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICE_CHANGE) // 捕获USB设备的拔出消息WM_DEVICECHANGE
            {
                switch (m.WParam.ToInt32())
                {
                    case DBT_DEVICE_REMOVE_COMPLETE: // USB拔出 
                        {

                            new Thread(
                                new ThreadStart(
                                    new Action(() =>
                                    {
                                        getPortDeviceName();
                                    })
                                )
                            ).Start();
                        }
                    break;
                    case DBT_DEVICEARRIVAL: // USB插入获取对应串口名称     
                    {
                            new Thread(
                                new ThreadStart(
                                    new Action(() =>
                                    {
                                        getPortDeviceName();
                                    })
                                )
                            ).Start();
                        }
                    break;
                }
            }
            base.WndProc(ref m);
        }

猜你喜欢

转载自blog.csdn.net/PZ0605/article/details/107863157