C# 获取蓝牙组件名称

C# 获取蓝牙组件名称,c#,windows,bluetooth,C#,Windows,Bluetooth,有没有办法枚举所有蓝牙com端口并获取它们的名称? 我所说的名字不是指COM10,在本例中,我指的是GNSS:51622“GNSS服务器” 使用32英尺,我已经能够找到端口的名称,但仍然没有运气将它们映射到实际的com端口 class Program { static void Main(string[] args) { Console.WriteLine("Connecting to Bluetooth"); var client = new

有没有办法枚举所有蓝牙com端口并获取它们的名称? 我所说的名字不是指
COM10
,在本例中,我指的是
GNSS:51622“GNSS服务器”

使用32英尺,我已经能够找到端口的名称,但仍然没有运气将它们映射到实际的com端口

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Connecting to Bluetooth");
        var client = new BluetoothClient();
        Console.WriteLine("DiscoverDevices");
        var devices = client.DiscoverDevices();
        Console.WriteLine("Enumerating");
        foreach (var device in devices)
        {
            if (!device.DeviceName.StartsWith("GNSS"))
                continue;
            Console.WriteLine(device.DeviceName);
            try
            {
                Console.WriteLine("Getting serial ports");
                var serviceRecords = device.GetServiceRecords(BluetoothService.SerialPort);
                foreach (var serviceRecord in serviceRecords)
                {
                    var name = GetName(serviceRecord);
                    Console.WriteLine(name);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to get SerialPort");
                Console.WriteLine(ex.ToString());
            }
        }
        Console.ReadKey();
    }

    private static string GetName(ServiceRecord serviceRecord)
    {
        var nameAttribute = serviceRecord.SingleOrDefault(a => a.Id == 0);
        var name = serviceRecord.GetPrimaryMultiLanguageStringAttributeById(nameAttribute.Id);
        return name;
    }
}
输出:

连接到蓝牙
发现证据
列举
全球导航卫星系统:51622
获取串行端口
COM1
COM2
COM3
全球导航卫星系统服务器

我在这里发布了一个要点,其中包含枚举蓝牙虚拟COM端口的代码。服务记录中的端口名值存储在注册表中,因此可以根据安装API中的设备路径获取该值。它在gist代码中作为RemoteServiceName公开。例如,在我的Zebra打印机上,它返回“串行打印机”。我没有一台设备可以处理多个公开的服务,但这将为您提供上面显示的设备名称旁边的字符串,例如“GNSS服务器”、“COM1”等

代码:

使用系统;
使用System.Collections.Generic;
使用系统诊断;
使用System.Runtime.InteropServices;
使用系统文本;
命名空间蓝牙诊断
{
公共密封类蓝牙组件
{
/// 
///返回系统上所有蓝牙虚拟COM端口的集合。
/// 
/// 
公共静态IReadOnlyList FindAll()
{
列表端口=新列表();
IntPtr handle=NativeMethods.SetupDiGetClassDevs(参考NativeMethods.GUID\u DEVCLASS\u PORTS,null,IntPtr.Zero,NativeMethods.DIGCF.PRESENT);
if(handle!=IntPtr.Zero)
{
尝试
{
NativeMethods.SP_DEVINFO_DATA dat=新的NativeMethods.SP_DEVINFO_DATA();
dat.cbSize=Marshal.SizeOf(dat);
uint i=0;
while(NativeMethods.SetupDiEnumDeviceInfo(句柄,i++,ref-dat))
{
string remoteServiceName=string.Empty;
StringBuilder sbid=新的StringBuilder(256);
整数大小;
NativeMethods.SetupDiGetDeviceInstanceId(句柄、参考数据、sbid、sbid.Capacity、输出大小);
Debug.WriteLine(sbid);
long addr=GetBluetoothAddressFromDevicePath(sbid.ToString());
//仅当存在传出蓝牙端口时有效
如果(addr!=long.MinValue&&addr!=0)
{
IntPtr hkey=NativeMethods.SetupDiOpenDevRegKey(句柄,参考数据,NativeMethods.DICS.GLOBAL,0,NativeMethods.DIREG.DEV,1);
var key=Microsoft.Win32.RegistryKey.FromHandle(新的Microsoft.Win32.SafeHandles.SafeRegistryHandle(hkey,true));
对象名=key.GetValue(“端口名”);
var pkey=Microsoft.Win32.Registry.LocalMachine.OpenSubKey(“SYSTEM\\CurrentControlSet\\Services\\BTHPORT\\Parameters\\Devices\\”+addr.ToString(“x12”);
if(pkey!=null)
{
foreach(pkey.GetSubKeyNames()中的字符串nm)
{
如果(nm.StartWith(“服务”))
{
var skey=pkey.OpenSubKey(nm);
字符串s=sbid.ToString();
//来自设备id字符串的蓝牙服务uuid
int-ifirst=s.IndexOf(“{”);
字符串uuid=s.Substring(ifirst,s.IndexOf(“}”)-ifirst+1);
var-ukey=skey.OpenSubKey(uuid);
//设备id字符串中的实例id
字符串iid=s.Substring(s.LastIndexOf(“”)+1);
var instKey=ukey.OpenSubKey(iid);
//注册表项包含作为字节数组的服务名称
对象o=instKey.GetValue(“PriLangServiceName”);
如果(o!=null)
{
字节[]字符=o作为字节[];
remoteServiceName=Encoding.UTF8.GetString(chars.Trim();
}
}
}
}
Add(新的BluetoothComPort(sbid.ToString(),addr,name.ToString(),remoteServiceName));
key.Dispose();
}
}
}
最后
{
NativeMethods.SetupDiDestroyDeviceInfo列表(句柄);
}
}
返回端口;
}
私有字符串_deviceId;
私人long_蓝牙地址;
私有字符串_portName;
私有字符串_remoteServiceName;
内部BluetoothComPort(字符串deviceId、长bluetoothAddress、字符串portName、字符串remoteServiceName)
{
_deviceId=deviceId;
_蓝牙地址=蓝牙地址;
_portName=portName;
_remoteServiceName=remoteServiceName;
}
公共字符串设备ID
{
得到
{
返回设备ID;
}
}
公共长蓝牙地址
{
得到
{
返回蓝牙地址;
}
}
公共字符串端口名
{
得到
{
返回_portName;
}
}
公共字符串
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace BluetoothDiagnostics
{
    public sealed class BluetoothComPort
    {
        /// <summary>
        /// Returns a collection of all the Bluetooth virtual-COM ports on the system.
        /// </summary>
        /// <returns></returns>
        public static IReadOnlyList<BluetoothComPort> FindAll()
        {
            List<BluetoothComPort> ports = new List<BluetoothComPort>();

            IntPtr handle = NativeMethods.SetupDiGetClassDevs(ref NativeMethods.GUID_DEVCLASS_PORTS, null, IntPtr.Zero,  NativeMethods.DIGCF.PRESENT);
            if (handle != IntPtr.Zero)
            {
                try
                {


                    NativeMethods.SP_DEVINFO_DATA dat = new NativeMethods.SP_DEVINFO_DATA();
                    dat.cbSize = Marshal.SizeOf(dat);
                    uint i = 0;

                    while (NativeMethods.SetupDiEnumDeviceInfo(handle, i++, ref dat))
                    {
                        string remoteServiceName = string.Empty;
                        StringBuilder sbid = new StringBuilder(256);
                        int size;
                        NativeMethods.SetupDiGetDeviceInstanceId(handle, ref dat, sbid, sbid.Capacity, out size);
                        Debug.WriteLine(sbid);
                        long addr = GetBluetoothAddressFromDevicePath(sbid.ToString());

                        // only valid if an outgoing Bluetooth port
                        if (addr != long.MinValue && addr != 0)
                        {
                            IntPtr hkey = NativeMethods.SetupDiOpenDevRegKey(handle, ref dat, NativeMethods.DICS.GLOBAL, 0, NativeMethods.DIREG.DEV, 1);
                            var key = Microsoft.Win32.RegistryKey.FromHandle(new Microsoft.Win32.SafeHandles.SafeRegistryHandle(hkey, true));
                            object name = key.GetValue("PortName");

                            var pkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\BTHPORT\\Parameters\\Devices\\" + addr.ToString("x12"));
                            if (pkey != null)
                            {
                                foreach (string nm in pkey.GetSubKeyNames())
                                {
                                    if (nm.StartsWith("ServicesFor"))
                                    {
                                        var skey = pkey.OpenSubKey(nm);
                                        string s = sbid.ToString();

                                        //bluetooth service uuid from device id string
                                        int ifirst = s.IndexOf("{");
                                        string uuid = s.Substring(ifirst, s.IndexOf("}") - ifirst+1);
                                        var ukey = skey.OpenSubKey(uuid);

                                        // instance id from device id string
                                        string iid = s.Substring(s.LastIndexOf("_")+1);
                                        var instKey = ukey.OpenSubKey(iid);

                                        // registry key contains service name as a byte array
                                        object o = instKey.GetValue("PriLangServiceName");
                                        if(o != null)
                                        {
                                            byte[] chars = o as byte[];
                                            remoteServiceName = Encoding.UTF8.GetString(chars).Trim();
                                        }
                                    }
                                }
                            }
                            ports.Add(new BluetoothComPort(sbid.ToString(), addr, name.ToString(), remoteServiceName));
                            key.Dispose();
                        }
                    }

                }
                finally
                {
                    NativeMethods.SetupDiDestroyDeviceInfoList(handle);
                }
            }

            return ports;
        }

        private string _deviceId;
        private long _bluetoothAddress;
        private string _portName;
        private string _remoteServiceName;

        internal BluetoothComPort(string deviceId, long bluetoothAddress, string portName, string remoteServiceName)
        {
            _deviceId = deviceId;
            _bluetoothAddress = bluetoothAddress;
            _portName = portName;
            _remoteServiceName = remoteServiceName;
        }

        public string DeviceId
        {
            get
            {
                return _deviceId;
            }
        }

        public long BluetoothAddress
        {
            get
            {
                return _bluetoothAddress;
            }
        }

        public string PortName
        {
            get
            {
                return _portName;
            }
        }

        public string RemoteServiceName
        {
            get
            {
                return _remoteServiceName;
            }
        }


        private static long GetBluetoothAddressFromDevicePath(string path)
        {
            if (path.StartsWith("BTHENUM"))
            {
                int start = path.LastIndexOf('&');
                int end = path.LastIndexOf('_');
                string addressString = path.Substring(start + 1, (end - start) - 1);

                // may return zero if it is an incoming port (we're not interested in these)
                return long.Parse(addressString, System.Globalization.NumberStyles.HexNumber);

            }

            // not a bluetooth port
            return long.MinValue;
        }

        private static class NativeMethods
        {
            // The SetupDiGetClassDevs function returns a handle to a device information set that contains requested device information elements for a local machine. 
            [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
            internal static extern IntPtr SetupDiGetClassDevs(
                ref Guid classGuid,
                [MarshalAs(UnmanagedType.LPTStr)] string enumerator,
                IntPtr hwndParent,
                DIGCF flags);

            // The SetupDiEnumDeviceInfo function returns a SP_DEVINFO_DATA structure that specifies a device information element in a device information set. 
            [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool SetupDiEnumDeviceInfo(
                IntPtr deviceInfoSet,
                uint memberIndex,
                ref SP_DEVINFO_DATA deviceInfoData);

            // The SetupDiDestroyDeviceInfoList function deletes a device information set and frees all associated memory.
            [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);

            // The SetupDiGetDeviceInstanceId function retrieves the device instance ID that is associated with a device information element.
            [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool SetupDiGetDeviceInstanceId(
               IntPtr deviceInfoSet,
               ref SP_DEVINFO_DATA deviceInfoData,
               System.Text.StringBuilder deviceInstanceId,
               int deviceInstanceIdSize,
               out int requiredSize);

            //static Guid GUID_DEVCLASS_BLUETOOTH = new Guid("{E0CBF06C-CD8B-4647-BB8A-263B43F0F974}");
            internal static Guid GUID_DEVCLASS_PORTS = new Guid("{4d36e978-e325-11ce-bfc1-08002be10318}");

            [DllImport("setupapi.dll", SetLastError = true)]
            internal static extern IntPtr SetupDiOpenDevRegKey(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData,
                DICS Scope, int HwProfile, DIREG KeyType, int samDesired);

            [Flags]
            internal enum DICS
            {
                GLOBAL = 0x00000001,  // make change in all hardware profiles
                CONFIGSPECIFIC = 0x00000002,  // make change in specified profile only
            }

            internal enum DIREG
            {
                DEV = 0x00000001,          // Open/Create/Delete device key
                DRV = 0x00000002,          // Open/Create/Delete driver key
            }

            // changes to follow.
            // SETUPAPI.H
            [Flags()]
            internal enum DIGCF
            {
                PRESENT = 0x00000002, // Return only devices that are currently present in a system.
                ALLCLASSES = 0x00000004, // Return a list of installed devices for all device setup classes or all device interface classes. 
                PROFILE = 0x00000008, // Return only devices that are a part of the current hardware profile.
            }


            [StructLayout(LayoutKind.Sequential)]
            internal struct SP_DEVINFO_DATA
            {
                internal int cbSize; // = (uint)Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
                internal Guid ClassGuid;
                internal uint DevInst;
                internal IntPtr Reserved;
            }
        }
    }
}