/************************************************************************************\ * CatLog - An SDSG Production * \************************************************************************************/ /*! \file SelectPortDialog.cs * \author Andrew Shurney * \brief Presents a dialog to choose from available ports. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.Management; using Microsoft.Win32; namespace CatLog { public partial class SelectPortDialog : Form { public class SelectPortItem { public String Text { get; set; } public String Value { get; set; } public override string ToString() { return Text; } } public SelectPortDialog(String portName) { InitializeComponent(); Dictionary ports = BuildPortNameHash(SerialPort.GetPortNames()); foreach (KeyValuePair port in ports) { SelectPortItem item = new SelectPortItem(); item.Text = port.Value; item.Value = port.Key; cmbPorts.Items.Add(item); if(port.Key == portName) cmbPorts.SelectedItem = item; } } public static Dictionary BuildPortNameHash(String[] portsToMap) { Dictionary oReturnTable = new Dictionary(); MineRegistryForPortName("SYSTEM\\CurrentControlSet\\Enum", oReturnTable, portsToMap); return oReturnTable; } static void MineRegistryForPortName(String startKeyPath, Dictionary targetMap, String[] portsToMap) { if (targetMap.Count >= portsToMap.Length) return; using (RegistryKey currentKey = Registry.LocalMachine) { try { using (RegistryKey currentSubKey = currentKey.OpenSubKey(startKeyPath)) { String[] currentSubkeys = currentSubKey.GetSubKeyNames(); if (currentSubkeys.Contains("Device Parameters") && startKeyPath != "SYSTEM\\CurrentControlSet\\Enum") { Object portName = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + startKeyPath + "\\Device Parameters", "PortName", null); if (portName == null || portsToMap.Contains(portName.ToString()) == false) return; Object friendlyPortName = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + startKeyPath, "FriendlyName", null); String friendlyName = "N/A"; if (friendlyPortName != null) friendlyName = friendlyPortName.ToString(); if (friendlyName.Contains(portName.ToString()) == false) friendlyName = String.Format("{0} ({1})", friendlyName, portName); targetMap[portName.ToString()] = friendlyName; } else { foreach (String strSubKey in currentSubkeys) MineRegistryForPortName(startKeyPath + "\\" + strSubKey, targetMap, portsToMap); } } } catch (Exception) { Console.WriteLine("Error accessing key '{0}'.. Skipping..", startKeyPath); } } } public String Port { get { SelectPortItem item = cmbPorts.SelectedItem as SelectPortItem; return item.Value; } } public String PortDesc { get { SelectPortItem item = cmbPorts.SelectedItem as SelectPortItem; return item.Text; } } } }