如何在Windows中通过C#获取已连接蓝牙设备属性?代码运行报错
Windows下C#获取已连接蓝牙设备的解决方案
原代码失效大概率是BluetoothDevice.GetDeviceSelectorFromConnectionStatusAPI在新Windows SDK版本中行为变更,或是权限配置缺失,以下是几种可行的替代方案:
方案一:枚举所有蓝牙设备并筛选已连接状态
这种方式兼容性更强,适用于UWP和适配WinRT的桌面应用:
// 获取所有蓝牙设备 var allBluetoothDevices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelector()); var connectedDevices = new List<DeviceInformation>(); foreach (var deviceInfo in allBluetoothDevices) { // 通过设备ID获取蓝牙设备实例 var bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfo.Id); if (bluetoothDevice != null && bluetoothDevice.ConnectionStatus == BluetoothConnectionStatus.Connected) { connectedDevices.Add(deviceInfo); // 读取设备属性示例 string deviceName = deviceInfo.Name; string deviceId = deviceInfo.Id; bool isPaired = bluetoothDevice.DeviceInformation.Pairing.IsPaired; } }
方案二:添加必要权限配置
无论哪种方案,都需要确保应用拥有蓝牙访问权限:
- 若为UWP应用,在
Package.appxmanifest中添加蓝牙设备能力:
<Capabilities> <DeviceCapability Name="bluetooth"/> </Capabilities>
- 若为桌面应用(WPF/WinForms),需在系统设置中允许应用访问蓝牙,或在应用清单中声明对应权限。
方案三:使用Win32 Bluetooth API(兼容旧版Windows)
如果需要兼容更旧的Windows版本,可通过P/Invoke调用原生Win32蓝牙API:
using System.Runtime.InteropServices; using System; public static class BluetoothHelper { [StructLayout(LayoutKind.Sequential)] private struct SYSTEMTIME { public ushort wYear; public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds; } [StructLayout(LayoutKind.Sequential)] private struct BLUETOOTH_DEVICE_INFO { public int dwSize; public ulong Address; public uint ulClassofDevice; public bool fConnected; public bool fRemembered; public bool fAuthenticated; public SYSTEMTIME stLastSeen; public SYSTEMTIME stLastUsed; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 248)] public string szName; } [DllImport("BluetoothAPIs.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool BluetoothEnumerateDevices(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO pDeviceInfo, ref uint pcDevices); public static List<string> GetConnectedBluetoothDevices() { var connectedDevices = new List<string>(); BLUETOOTH_DEVICE_INFO deviceInfo = new BLUETOOTH_DEVICE_INFO(); deviceInfo.dwSize = Marshal.SizeOf(deviceInfo); uint deviceCount = 0; // 先获取设备数量 BluetoothEnumerateDevices(IntPtr.Zero, ref deviceInfo, ref deviceCount); if (deviceCount > 0) { for (uint i = 0; i < deviceCount; i++) { if (BluetoothEnumerateDevices(IntPtr.Zero, ref deviceInfo, ref i)) { if (deviceInfo.fConnected) { connectedDevices.Add(deviceInfo.szName); } } } } return connectedDevices; } }
调用方式:
var connectedDeviceNames = BluetoothHelper.GetConnectedBluetoothDevices();
内容的提问来源于stack exchange,提问作者Tom Xue
相关产品推荐
相关产品推荐

