2011-03-26 36 views
10

我有一個非常小的代碼,顯示可用的COM端口。列出可用的COM端口

我的問題是:

有一種簡單的方法來使程序在托盤和僅彈出運行在一個新的COM端口是可用的,並且有可能COM端口添加姓名,你可以在設備管理器中看到「USB串口」?

我經常添加/移除一個USB-> RS232轉換器,並發現它是一個痛苦的屁股,因爲我必須進入設備管理器查看它分配給哪個COM端口。每次

這是不一樣的也許已經有一個小的應用程序,可以做到這一點,但我還沒有發現它在谷歌尚未

using System; 
using System.Windows.Forms; 
using System.IO.Ports; 

namespace Available_COMports 

{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
    { 
     InitializeComponent(); 

     //show list of valid com ports 
     foreach (string s in SerialPort.GetPortNames()) 
     { 
      listBox1.Items.Add(s); 
     } 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
    } 

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
    } 
} 

}

回答

5

看看this question。它使用WMI來查找可用的COM端口。您可以跟蹤哪些COM端口存在,並只通知新的端口。

0

獲取某個設備的COM號的代碼。

List<USBDeviceInfo> devices = new List<USBDeviceInfo>(); 
ManagementObjectSearcher searcher = 
    new ManagementObjectSearcher("root\\CIMV2", 
    "SELECT * FROM Win32_PnPEntity"); 
foreach (ManagementObject queryObj in searcher.Get()) 
{ 
    devices.Add(new USBDeviceInfo(
     (string)queryObj["DeviceID"], 
     (string)queryObj["PNPDeviceID"], 
     (string)queryObj["Name"] 
    )); 
} 

foreach (USBDeviceInfo usbDevice in devices) 
{ 
    if (usbDevice.Description != null) 
    { 
     if (usbDevice.Description.Contains("NAME OF Device You are Looking for")) //use your own device's name 
     { 
      int i = usbDevice.Description.IndexOf("COM"); 
      char[] arr = usbDevice.Description.ToCharArray(); 
      str = "COM" + arr[i + 3]; 
      if (arr[i + 4] != ')') 
      { 
       str += arr[i + 4]; 
      } 
      break; 
     } 
    } 
} 

mySerialPort = new SerialPort(str);