C# ardwareID(字符串fullHardwareID) { int-length=fullHardwareID.LastIndexOf(“”“); 返回fullHardwareID.Substring(0,长度); } 私有bool TryFindPair(字符串pairsName、字符串hardwareID、列表bluetoothCOMPorts、输出ComportComport) { foreach(蓝牙组件中的ManagementObject蓝牙组件) { 字符串itemHardwareID=((字符串[])bluetoothCOMPort[“HardwareID”])[0]; if(hardwareID!=itemHardwareID&&ExtractHardwareID(hardwareID)==ExtractHardwareID(itemHardwareID)) { comPort=new comPort(ExtractCOMPortFromName(bluetoothCOMPort[“Name”].ToString()),Direction.INCOMING,pairsName); 返回true; } } comPort=null; 返回false; } 私有字符串GetDataBunsName(字符串pnpDeviceID) { 使用(PowerShell PowerShellInstance=PowerShell.Create()) { PowerShellInstance.AddScript($@“Get-PnpDeviceProperty-InstanceId'{pnpDeviceID}'-KeyName'DEVPKEY_Device_BusReportedDeviceDesc'|选择对象数据”); 集合PSOutput=PowerShellInstance.Invoke(); foreach(PSOutput中的PSObject输出项) { if(outputItem!=null) { Console.WriteLine(outputItem.BaseObject.GetType().FullName); foreach(outputItem.Properties中的var p) { 如果(p.Name==“数据”) { 返回p.Value?.ToString(); } } } } } 返回字符串。空; } public void GetBluetoothCOMPort() { COMPorts.Clear(); ManagementObjectCollection结果=新建ManagementObjectSearcher( @“从Win32中选择PNPClass、PNPDeviceID、Name、HardwareID,其中(名称类似于“%COM%”,PNPDeviceID类似于“%BTHENUM%”,PNPClass=“Ports”)或(PNPClass=“Bluetooth”和PNPDeviceID类似于“%BTHENUM\\DEV%”)。Get(); List bluetoothCOMPorts=新列表(); List bluetoothDevices=新列表(); foreach(结果中的ManagementObject查询对象) { if(queryObj[“PNPClass”].ToString()=“蓝牙”) { bluetoothDevices.Add(queryObj); } else if(queryObj[“PNPClass”].ToString()=“端口”) { bluetoothCOMPorts.Add(queryObj); } } foreach(bluetoothDevices中的ManagementObject bluetoothDevice) { foreach(蓝牙组件中的ManagementObject蓝牙组件) { 字符串comPortPNPDeviceID=bluetoothCOMPort[“PNPDeviceID”].ToString(); if(ExtractBluetoothDevice(bluetoothDevice[“PNPDeviceID”].ToString())==ExtractDevice(comPortPNPDeviceID)) { COMPort outgoingPort=new COMPort(ExtractCOMPortFromName(bluetoothCOMPort[“Name”].ToString()),Direction.OUTGOING,$“{bluetoothDevice[“Name”].ToString()}\{GetDataBusName(comPortPNPDeviceID)}\”; Application.Current.Dispatcher.Invoke(()=>{ 组件添加(输出端口); }); if(TryFindPair(蓝牙设备[“名称”].ToString(),((字符串[])蓝牙组件[“硬件ID”])[0],蓝牙组件,输出组件输入端口)) { Application.Current.Dispatcher.Invoke(()=>{ 组件添加(输入端口); }); } } } } } } 公共类组件:INotifyPropertyChanged { 公共事件属性更改事件处理程序属性更改; 私有void RaisePropertyChanged([CallerMemberName]字符串propertyName=null) { PropertyChanged?.Invoke(这是新的PropertyChangedEventArgs(propertyName)); } 私有字符串复合端口; 公共字符串串行端口 { get=>comPortPort; 设置 { comPortPort=值; RaisePropertyChanged(); } } 私人指导; 公共方向 { get=>comPortDirection; 设置 { comPortDirection=值; RaisePropertyChanged(); } } 私有字符串comPortName; 公共字符串名 { get=>comPortName; 设置 { comPortName=值; RaisePropertyChanged(); } } 公共组件(字符串组件端口、方向组件方向、字符串组件名称) { SerialPort=comPortPort; 方向=复合方向; 名称=组件名称; } } 公共类方向转换器 { 私有常量字符串未定义\u DIRECTION=“未定义”; 私有常量字符串传入\u DIRECTION=“传入”; private const string OUTGOING_DIRECTION=“OUTGOING”; 公共对象转换(对象值、类型targetType、对象参数、CultureInfo区域性) { 开关((方向)值) { 案例方向。未定义: 返回未定义的_方向; 案例说明。传入: 返回输入方向; 案例说明.输出: 返回输出方向; } 返回字符串。空; } 公共对象转换回(对象值、类型targetType、对象参数、CultureInfo区域性) { 抛出新的NotImplementedException(); } } 公共枚举方向 { 未定义, 新当选的 外向的 }
网址:C# ardwareID(字符串fullHardwareID) { int-length=fullHardwareID.LastIndexOf(“”“); 返回fullHardwareID.Substring(0,长度); } 私有bool TryFindPair(字符串pairsName、字符串hardwareID、列表bluetoothCOMPorts、输出ComportComport) { foreach(蓝牙组件中的ManagementObject蓝牙组件) { 字符串itemHardwareID=((字符串[])bluetoothCOMPort[“HardwareID”])[0]; if(hardwareID!=itemHardwareID&&ExtractHardwareID(hardwareID)==ExtractHardwareID(itemHardwareID)) { comPort=new comPort(ExtractCOMPortFromName(bluetoothCOMPort[“Name”].ToString()),Direction.INCOMING,pairsName); 返回true; } } comPort=null; 返回false; } 私有字符串GetDataBunsName(字符串pnpDeviceID) { 使用(PowerShell PowerShellInstance=PowerShell.Create()) { PowerShellInstance.AddScript($@“Get-PnpDeviceProperty-InstanceId'{pnpDeviceID}'-KeyName'DEVPKEY_Device_BusReportedDeviceDesc'|选择对象数据”); 集合PSOutput=PowerShellInstance.Invoke(); foreach(PSOutput中的PSObject输出项) { if(outputItem!=null) { Console.WriteLine(outputItem.BaseObject.GetType().FullName); foreach(outputItem.Properties中的var p) { 如果(p.Name==“数据”) { 返回p.Value?.ToString(); } } } } } 返回字符串。空; } public void GetBluetoothCOMPort() { COMPorts.Clear(); ManagementObjectCollection结果=新建ManagementObjectSearcher( @“从Win32中选择PNPClass、PNPDeviceID、Name、HardwareID,其中(名称类似于“%COM%”,PNPDeviceID类似于“%BTHENUM%”,PNPClass=“Ports”)或(PNPClass=“Bluetooth”和PNPDeviceID类似于“%BTHENUM\\DEV%”)。Get(); List bluetoothCOMPorts=新列表(); List bluetoothDevices=新列表(); foreach(结果中的ManagementObject查询对象) { if(queryObj[“PNPClass”].ToString()=“蓝牙”) { bluetoothDevices.Add(queryObj); } else if(queryObj[“PNPClass”].ToString()=“端口”) { bluetoothCOMPorts.Add(queryObj); } } foreach(bluetoothDevices中的ManagementObject bluetoothDevice) { foreach(蓝牙组件中的ManagementObject蓝牙组件) { 字符串comPortPNPDeviceID=bluetoothCOMPort[“PNPDeviceID”].ToString(); if(ExtractBluetoothDevice(bluetoothDevice[“PNPDeviceID”].ToString())==ExtractDevice(comPortPNPDeviceID)) { COMPort outgoingPort=new COMPort(ExtractCOMPortFromName(bluetoothCOMPort[“Name”].ToString()),Direction.OUTGOING,$“{bluetoothDevice[“Name”].ToString()}\{GetDataBusName(comPortPNPDeviceID)}\”; Application.Current.Dispatcher.Invoke(()=>{ 组件添加(输出端口); }); if(TryFindPair(蓝牙设备[“名称”].ToString(),((字符串[])蓝牙组件[“硬件ID”])[0],蓝牙组件,输出组件输入端口)) { Application.Current.Dispatcher.Invoke(()=>{ 组件添加(输入端口); }); } } } } } } 公共类组件:INotifyPropertyChanged { 公共事件属性更改事件处理程序属性更改; 私有void RaisePropertyChanged([CallerMemberName]字符串propertyName=null) { PropertyChanged?.Invoke(这是新的PropertyChangedEventArgs(propertyName)); } 私有字符串复合端口; 公共字符串串行端口 { get=>comPortPort; 设置 { comPortPort=值; RaisePropertyChanged(); } } 私人指导; 公共方向 { get=>comPortDirection; 设置 { comPortDirection=值; RaisePropertyChanged(); } } 私有字符串comPortName; 公共字符串名 { get=>comPortName; 设置 { comPortName=值; RaisePropertyChanged(); } } 公共组件(字符串组件端口、方向组件方向、字符串组件名称) { SerialPort=comPortPort; 方向=复合方向; 名称=组件名称; } } 公共类方向转换器 { 私有常量字符串未定义\u DIRECTION=“未定义”; 私有常量字符串传入\u DIRECTION=“传入”; private const string OUTGOING_DIRECTION=“OUTGOING”; 公共对象转换(对象值、类型targetType、对象参数、CultureInfo区域性) { 开关((方向)值) { 案例方向。未定义: 返回未定义的_方向; 案例说明。传入: 返回输入方向; 案例说明.输出: 返回输出方向; } 返回字符串。空; } 公共对象转换回(对象值、类型targetType、对象参数、CultureInfo区域性) { 抛出新的NotImplementedException(); } } 公共枚举方向 { 未定义, 新当选的 外向的 },c#,bluetooth,serial-port,C#,Bluetooth,Serial Port,网址: 谢谢您的代码片段,但它没有返回我想要的名称。我试图在ports[x].Properties集合中搜索,但在屏幕截图的“name”(“nome”)字段中找不到相同的名称。你有没有搞错? public static bool DoesSerialDeviceExist(string name) { using (var search = new ManagementObjectSearcher ("SELECT * FROM WIN32
谢谢您的代码片段,但它没有返回我想要的名称。我试图在ports[x].Properties集合中搜索,但在屏幕截图的“name”(“nome”)字段中找不到相同的名称。你有没有搞错?
public static bool DoesSerialDeviceExist(string name)
{
using (var search = new ManagementObjectSearcher
("SELECT * FROM WIN32_SerialPort"))
{
string[] portnames = SerialPort.GetPortNames();
var ports = search.Get().Cast<ManagementBaseObject>().ToList();
var tList = (from n in portnames
join p in ports on n equals p["DeviceID"].ToString()
select n + " - " + p["Caption"]).ToList();
string serial = tList.FirstOrDefault(o => o.Contains(name));
bool isAvailable = false;
if (serial != null)
{
isAvailable = true;
}
return isAvailable;
}
}
private void FillInComportComboBox()
{
Hashtable PortNames = new Hashtable();
string[] ports = System.IO.Ports.SerialPort.GetPortNames();
//string st = ComPortList.Text;
ComPortList.Items.Clear();
if (ports.Length == 0)
{
ComPortList.Items.Add("ERROR: No COM ports exist");
}
else
{
PortNames = BuildPortNameHash(ports);
//foreach (string s in ports)
foreach(String s in PortNames.Keys)
{
//ComPortList.Items.Add(s + ": " + (string)PortNames[s]);
ComPortList.Items.Add(PortNames[s] + ": " + s);
}
}
}
// Begins recursive registry enumeration
// <param name="oPortsToMap">array of port names (i.e. COM1, COM2, etc)</param>
// <returns>a hashtable mapping Friendly names to non-friendly port values</returns>
Hashtable BuildPortNameHash(string[] oPortsToMap)
{
Hashtable oReturnTable = new Hashtable();
MineRegistryForPortName("SYSTEM\\CurrentControlSet\\Enum", oReturnTable, oPortsToMap);
return oReturnTable;
}
// Recursively enumerates registry subkeys starting with strStartKey looking for
// "Device Parameters" subkey. If key is present, friendly port name is extracted.
// <param name="strStartKey">the start key from which to begin the enumeration</param>
// <param name="oTargetMap">hashtable that will get populated with
// friendly-to-nonfriendly port names</param>
// <param name="oPortNamesToMatch">array of port names (i.e. COM1, COM2, etc)</param>
void MineRegistryForPortName(string strStartKey, Hashtable oTargetMap, string[] oPortNamesToMatch)
{
if (oTargetMap.Count >= oPortNamesToMatch.Length)
return;
RegistryKey oCurrentKey = Registry.LocalMachine;
try
{
oCurrentKey = oCurrentKey.OpenSubKey(strStartKey);
string[] oSubKeyNames = oCurrentKey.GetSubKeyNames();
if (((IList<string>)oSubKeyNames).Contains("Device Parameters") && strStartKey != "SYSTEM\\CurrentControlSet\\Enum")
{
object oPortNameValue = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + strStartKey + "\\Device Parameters", "PortName", null);
if (oPortNameValue == null || ((IList<string>)oPortNamesToMatch).Contains(oPortNameValue.ToString()) == false)
return;
object oFriendlyName = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + strStartKey, "FriendlyName", null);
string strFriendlyName = "N/A";
if (oFriendlyName != null)
strFriendlyName = oFriendlyName.ToString();
if (strFriendlyName.Contains(oPortNameValue.ToString()) == false)
strFriendlyName = string.Format("{0} ({1})", strFriendlyName, oPortNameValue);
oTargetMap[strFriendlyName] = oPortNameValue;
//oTargetMap[oPortNameValue] = strFriendlyName;
}
else
{
foreach (string strSubKey in oSubKeyNames)
MineRegistryForPortName(strStartKey + "\\" + strSubKey, oTargetMap, oPortNamesToMatch);
}
}
catch
{
}
}
Main()
{
AvailablePorts ports = new AvailablePorts();
ports.GetBluetoothCOMPort();
System.Collections.ObjectModel.ObservableCollection<COMPort> obs = ports.COMPorts;
}
using System;
using System.Collections.Generic;
using System.Management;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Windows;
using System.Management.Automation;
public class AvailablePorts
{
private ObservableCollection<COMPort> comPorts = new ObservableCollection<COMPort>();
public ObservableCollection<COMPort> COMPorts
{
get => comPorts;
set
{
comPorts = value;
}
}
private string ExtractBluetoothDevice(string pnpDeviceID)
{
int startPos = pnpDeviceID.LastIndexOf('_') + 1;
return pnpDeviceID.Substring(startPos);
}
private string ExtractDevice(string pnpDeviceID)
{
int startPos = pnpDeviceID.LastIndexOf('&') + 1;
int length = pnpDeviceID.LastIndexOf('_') - startPos;
return pnpDeviceID.Substring(startPos, length);
}
private string ExtractCOMPortFromName(string name)
{
int openBracket = name.IndexOf('(');
int closeBracket = name.IndexOf(')');
return name.Substring(openBracket + 1, closeBracket - openBracket - 1);
}
private string ExtractHardwareID(string fullHardwareID)
{
int length = fullHardwareID.LastIndexOf('_');
return fullHardwareID.Substring(0, length);
}
private bool TryFindPair(string pairsName, string hardwareID, List<ManagementObject> bluetoothCOMPorts, out COMPort comPort)
{
foreach (ManagementObject bluetoothCOMPort in bluetoothCOMPorts)
{
string itemHardwareID = ((string[])bluetoothCOMPort["HardwareID"])[0];
if (hardwareID != itemHardwareID && ExtractHardwareID(hardwareID) == ExtractHardwareID(itemHardwareID))
{
comPort = new COMPort(ExtractCOMPortFromName(bluetoothCOMPort["Name"].ToString()), Direction.INCOMING, pairsName);
return true;
}
}
comPort = null;
return false;
}
private string GetDataBusName(string pnpDeviceID)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript($@"Get-PnpDeviceProperty -InstanceId '{pnpDeviceID}' -KeyName 'DEVPKEY_Device_BusReportedDeviceDesc' | select-object Data");
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
foreach (PSObject outputItem in PSOutput)
{
if (outputItem != null)
{
Console.WriteLine(outputItem.BaseObject.GetType().FullName);
foreach (var p in outputItem.Properties)
{
if (p.Name == "Data")
{
return p.Value?.ToString();
}
}
}
}
}
return string.Empty;
}
public void GetBluetoothCOMPort()
{
COMPorts.Clear();
ManagementObjectCollection results = new ManagementObjectSearcher(
@"SELECT PNPClass, PNPDeviceID, Name, HardwareID FROM Win32_PnPEntity WHERE (Name LIKE '%COM%' AND PNPDeviceID LIKE '%BTHENUM%' AND PNPClass = 'Ports') OR (PNPClass = 'Bluetooth' AND PNPDeviceID LIKE '%BTHENUM\\DEV%')").Get();
List<ManagementObject> bluetoothCOMPorts = new List<ManagementObject>();
List<ManagementObject> bluetoothDevices = new List<ManagementObject>();
foreach (ManagementObject queryObj in results)
{
if (queryObj["PNPClass"].ToString() == "Bluetooth")
{
bluetoothDevices.Add(queryObj);
}
else if (queryObj["PNPClass"].ToString() == "Ports")
{
bluetoothCOMPorts.Add(queryObj);
}
}
foreach (ManagementObject bluetoothDevice in bluetoothDevices)
{
foreach (ManagementObject bluetoothCOMPort in bluetoothCOMPorts)
{
string comPortPNPDeviceID = bluetoothCOMPort["PNPDeviceID"].ToString();
if (ExtractBluetoothDevice(bluetoothDevice["PNPDeviceID"].ToString()) == ExtractDevice(comPortPNPDeviceID))
{
COMPort outgoingPort = new COMPort(ExtractCOMPortFromName(bluetoothCOMPort["Name"].ToString()), Direction.OUTGOING, $"{bluetoothDevice["Name"].ToString()} \'{GetDataBusName(comPortPNPDeviceID)}\'");
Application.Current.Dispatcher.Invoke(() => {
COMPorts.Add(outgoingPort);
});
if (TryFindPair(bluetoothDevice["Name"].ToString(), ((string[])bluetoothCOMPort["HardwareID"])[0], bluetoothCOMPorts, out COMPort incomingPort))
{
Application.Current.Dispatcher.Invoke(() => {
COMPorts.Add(incomingPort);
});
}
}
}
}
}
}
public class COMPort : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string comPortPort;
public string SerialPort
{
get => comPortPort;
set
{
comPortPort = value;
RaisePropertyChanged();
}
}
private Direction comPortDirection;
public Direction Direction
{
get => comPortDirection;
set
{
comPortDirection = value;
RaisePropertyChanged();
}
}
private string comPortName;
public string Name
{
get => comPortName;
set
{
comPortName = value;
RaisePropertyChanged();
}
}
public COMPort(string comPortPort, Direction comPortDirection, string comPortName)
{
SerialPort = comPortPort;
Direction = comPortDirection;
Name = comPortName;
}
}
public class DirectionConverter
{
private const string UNDEFINED_DIRECTION = "UNDEFINED";
private const string INCOMING_DIRECTION = "Incoming";
private const string OUTGOING_DIRECTION = "Outgoing";
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch ((Direction)value)
{
case Direction.UNDEFINED:
return UNDEFINED_DIRECTION;
case Direction.INCOMING:
return INCOMING_DIRECTION;
case Direction.OUTGOING:
return OUTGOING_DIRECTION;
}
return string.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public enum Direction
{
UNDEFINED,
INCOMING,
OUTGOING
}