友好的端口名组合框c#Windows窗体
我有一个关于友好名字的问题,我读了很多关于如何得到友好名字的书。我甚至使用了WMICodeCreator,我有一个代码要放。但实际上,我不明白如何将它添加到我的组合框菜单中。这是我的密码。实际上,这一个显示了计算机上可用的COM端口,但我想显示这一个的friendlyname,以使我的应用程序更易于使用。如何显示friendlyname而不是“COMx”? 我正在C#上使用Windows窗体应用程序友好的端口名组合框c#Windows窗体,c#,combobox,windows-forms-designer,C#,Combobox,Windows Forms Designer,我有一个关于友好名字的问题,我读了很多关于如何得到友好名字的书。我甚至使用了WMICodeCreator,我有一个代码要放。但实际上,我不明白如何将它添加到我的组合框菜单中。这是我的密码。实际上,这一个显示了计算机上可用的COM端口,但我想显示这一个的friendlyname,以使我的应用程序更易于使用。如何显示friendlyname而不是“COMx”? 我正在C#上使用Windows窗体应用程序 提前感谢您的帮助这是一个老问题,但它是在我搜索相关内容时出现的,因此我将发布用于此确切目的的代码
提前感谢您的帮助这是一个老问题,但它是在我搜索相关内容时出现的,因此我将发布用于此确切目的的代码 我从SerialPort获取端口名列表,然后将它们与从WMI查询检索到的友好名称列表进行匹配,并将它们放入字典中,以端口名作为键,友好名称作为值。然后我使用这个字典作为组合框的绑定源。还有其他方法可以做到这一点,但我发现这种方法简单明了 这个术语有点混乱,因为组合框有一个DisplayMember,它将用来显示文本,还有一个ValueMember,它将作为SelectedValue提供。DisplayMember是字典“值”,ValueMember是字典“键”
我希望这能帮助别人 试着我用了所有的页面,所有的代码,试着添加很多行,移动,更改所有的压缩所有我能读到的,什么都不做,它充满了错误信息。尤其是使用
ManagementObjectSearcher
public partial class Form1 : Form
{
private SerialPort myport;
public Form1()
{
InitializeComponent();
myport = new SerialPort();
}
private void portbox_DropDown(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
portbox.Items.Clear();
foreach (string port in ports)
{
portbox.Items.Add(port);
}
}
private void butvalidate_Click(object sender, EventArgs e)
{
myport.BaudRate = 9600;
myport.PortName = portbox.SelectedItem.ToString();
myport.Open();
}
using System.Management;
private void getAvailablePorts()
{
// Get friendly names to go along with the actual portNames
using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SERIALPORT"))
{
var portDictionary = new Dictionary<string, string>();
var portNames = SerialPort.GetPortNames().OrderByDescending(s => s.GetAlphaNumericOrderToken()).ToArray<object>();
var portList = searcher.Get().Cast<ManagementBaseObject>().ToList();
foreach( var portName in portNames)
{
// WMI does not always find all com ports so provide a null alternative
var portDesc = portList.Where(p => p["DeviceID"].ToString() == portName.ToString()).Select(q => q["Caption"].ToString()).FirstOrDefault() ?? portName.ToString();
portDictionary.Add(portName.ToString(), portDesc);
}
portComboBox.DataSource = new BindingSource(portDictionary, null);
portComboBox.DisplayMember = "Value";
portComboBox.ValueMember = "Key";
// I set my comboBox Selected entry to be the one with a friendly name
// beginning with "Teensy" (of course yours will be different,
// or you can leave this out)
portComboBox.SelectedIndex = portComboBox.FindString("Teensy"); // -1 if not found
if (portComboBox.SelectedIndex < 0)
portComboBox.Selected = 0;
}
}
// Since the ComboBox text is now different from the value,
// you have to specifically get the SelectedValue of the ComboBox
// rather than just its text.
var _port = new SerialPort(portComboBox.SelectedValue.ToString());