2017-03-09 12 views
-1

我有一个串行程序,我用它来发送数据到打印机。 (Epson TM虚拟端口分配工具版本8.50) 在这种情况下,用于USB打印机的COM9,用于以太网打印机的COM13和用于以太网打印机的COM15用于COM端口并行打印机。我知道这听起来很奇怪,但效果很好。 我的问题是我有一个简单的foreach循环来获取COM端口名称。 我需要知道如何在组合框中重命名它们。 private string [] openComPorts = SerialPort.GetPortNames(); foreach(var openComPorts中的项) { comboBox1.Items.Add(item); }重命名COM端口后,我已经读了他们的名字

所以现在我的comboBox1显示COM1,COM3,COM4,COM9,COM13,COM15。 如何重命名COM9,13,15? 我想让他们说COM9-USB,COM13-以太网,COM15-并行 任何帮助,将不胜感激。 目标PC运行的是Windows 7,.NET 4.x版,SP1

+0

你知道你要使用的自定义名称提前时间? (I.E. COM9-USB) – BackDoorNoBaby

+0

是的,COM9-USB,COM13-Ethernet,COM15-Parallel,这样用户不需要记住哪些是哪个。 –

+0

您是否需要组合框中的所有COM端口,或仅需要您想要自定义名称的COM端口? – BackDoorNoBaby

回答

0

只是做一个字典使用查表为您的端口:

 string[] openComPorts = SerialPort.GetPortNames(); 
    Dictionary<string, string> dctLookups = new Dictionary<string, string>(); 

    // Loop through each COM port name and add to dictionary, giving 
    // it your custom name 
    foreach (string comPort in openComPorts) 
    { 
     // local variable to hold standard name of your port 
     string portName = comPort; 

     // Check for one of the ports you want a custom name for 
     if (comPort == "COM9") 
     { 
      portName += "-USB"; 
     } 
     else if (comPort == "COM13") 
     { 
      portName += "-Ethernet"; 
     } 
     else if (comPort == "COM15") 
     { 
      portName += "-Parallel"; 
     } 

     // Add to <key,value> dictionary with key being portName 
     dctLookups.Add(portName, comPort); 

     // Add custom name to combobox 
     comboBox1.Items.Add(portName); 
    } 

    // Get the actual COM port out of your dictionary like this 
    try 
    { 
     string comPort = dctLookups[comboBox1.SelectedItem.ToString()]; 
    } 
    catch (Exception) 
    { 
     // Port name not in your lookup table 
    } 
+0

这允许您维护一个表,其中的键是您分配的自定义值,并且该值是实际的COM端口名称。对于你不关心的COM端口,密钥和值将是相同的 – BackDoorNoBaby

+1

工作100%,实际上我正在寻找,非常感谢! :) –