[C#] Hiển thị tên đầy đủ của thiết bị tương ứng với từng cổng COM

MrChips

Thành Viên PIF
Đây là một đoạn code nhỏ để các bạn có thể biết được COM đó là thiết bị nào, tiện dụng hơn khi bạn phải vào Device Manager xem tên thiết bị đó là COMx nào đó rồi quay lại Form chọn :D
Yêu cầu Add một số thứ vào header như sau:
  • Add using System.IO;using System.IO.Ports; để sử dụng COM Ports
  • Add using System.Management; . Thông thường, khai báo xong hoặc là không có hoặc là bị lỗi. :gach Để không lỗi thì cần add thêm Reference System.Management bằng cách: Project -> Add Reference -> System.Management;
Vậy là đã xong, có thể code. Add vài class này vào và sử dụng thâu.
Code:
    internal class ProcessConnection
    {
        public static ConnectionOptions ProcessConnectionOptions()
        {
            ConnectionOptions options = new ConnectionOptions();
            options.Impersonation = ImpersonationLevel.Impersonate;
            options.Authentication = AuthenticationLevel.Default;
            options.EnablePrivileges = true;
            return options;
        }
 
        public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path)
        {
            ManagementScope connectScope = new ManagementScope();
            connectScope.Path = new ManagementPath(@"\\" + machineName + path);
            connectScope.Options = options;
            connectScope.Connect();
            return connectScope;
        }
    }
 
    public class COMPortInfo
    {
        public string Name { get; set; }
        public string Description { get; set; }
 
        public COMPortInfo() { }
 
        public static List<COMPortInfo> GetCOMPortsInfo()
        {
            List<COMPortInfo> comPortInfoList = new List<COMPortInfo>();
 
            ConnectionOptions options = ProcessConnection.ProcessConnectionOptions();
            ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2");
 
            ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
            ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery);
 
            using (comPortSearcher)
            {
                string caption = null;
                foreach (ManagementObject obj in comPortSearcher.Get())
                {
                    if (obj != null)
                    {
                        object captionObj = obj["Caption"];
                        if (captionObj != null)
                        {
                            caption = captionObj.ToString();
                            if (caption.Contains("(COM"))
                            {
                                COMPortInfo comPortInfo = new COMPortInfo();
                                comPortInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
                                comPortInfo.Description = caption;
                                comPortInfoList.Add(comPortInfo);
                            }
                        }
                    }
                }
            }
            return comPortInfoList;
        }
    }
Đặt tên cho cái ComboBox trong GUI là CbCOMPort nha!
Dùng timer1 cập nhật liên tục COM Ports
Code:
        int intlen=0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            if (intlen != ports.Length)
            {
                intlen = ports.Length;
                CbCOMPort.Items.Clear();
                foreach (COMPortInfo PortCOMs in COMPortInfo.GetCOMPortsInfo())
                {
                    CbCOMPort.Items.Add(string.Format("{0} – {1}", PortCOMs.Name, PortCOMs.Description));
                }
                CbCOMPort.SelectedIndex = 0;
            }
        }
Vậy là xong lun rồi đó.
Chúc may mắn và thành công! =))
Các bạn có thể nghiên cứu thêm qua link sau: màu hồng
 
Top