起初想到的方式是點選comboBox時用thread去搜尋comport節點
再用foreach去長出目前的節點
如程式:遍尋電腦裝置上已連接的comport device並顯示在comboBox上
foreach (string PortName in System.IO.Ports.SerialPort.GetPortNames())
{
comboBox1.Items.Add(PortName);
}
直到最近找到一個更適合的方式:
切記:此方法必須先引入 using System.Management;
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
{
List
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;
}
}
如下圖為片段
接著在 ui的程式碼中輸入下述:
private void FTM_DropDown(object sender, EventArgs e)
{
DL2_FTM_COM_COMBO.Items.Clear();
foreach (pilot_line_test.function.COMPortInfo comPort in pilot_line_test.function.COMPortInfo.GetCOMPortsInfo())
{
DL2_FTM_COM_COMBO.Items.Add(string.Format("{0} – {1}", comPort.Name, comPort.Description));
}
DL2_RS232_COM_COMBO.Items.Clear();
foreach (pilot_line_test.function.COMPortInfo comPort in pilot_line_test.function.COMPortInfo.GetCOMPortsInfo())
{
DL2_RS232_COM_COMBO.Items.Add(string.Format("{0} – {1}", comPort.Name, comPort.Description));
}
}
然後在ComboBox的物件屬性的DropDown選擇對應的類別名稱 FTM_DropDown
就大功告成,此方法可以動態插拔comport並且動態新增及找尋,非常之方便~分享給大家!!
沒有留言:
張貼留言