private async Task AddDeviceAsync() { SelectBluetoothDeviceDialog dialog = new SelectBluetoothDeviceDialog() { ShowRemembered = false, ShowAuthenticated = true, ShowUnknown = true }; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { BluetoothDeviceInfo selectedDevice = dialog.SelectedDevice; if (selectedDevice != null && !BluetoothDevices.Any(d => (d as BluetoothDeviceItem)?.DeviceInfo.DeviceAddress == selectedDevice.DeviceAddress)) { BluetoothDeviceItem item = await BluetoothDeviceItem.GetBluetoothDeviceItemAsync(selectedDevice); if (item == null) { MessageBox.Show("该设备没有可连接的服务", "错误"); } else { BluetoothDevices.Add(item); foreach (var s in item.Services) { allBluetoothItem.Insert(s); } } } } }
public static async Task <BluetoothDeviceItem> GetBluetoothDeviceItemAsync(BluetoothDeviceInfo info) { BluetoothDeviceItem device = new BluetoothDeviceItem() { FriendlyName = info.DeviceName, DeviceInfo = info }; List <Guid> services = device.DeviceInfo.InstalledServices.ToList(); if (!services.Contains(BluetoothService.SerialPort)) { services.Add(BluetoothService.SerialPort); } foreach (Guid service in services) { BluetoothServiceItem bluetoothService = await BluetoothServiceItem.GetBluetoothServiceItemAsync(device.DeviceInfo.DeviceAddress, service); if (bluetoothService != null) { bluetoothService.AppendLog("系统", $"{device.FriendlyName}的{bluetoothService.FriendlyName}服务已加入"); bluetoothService.Device = device; await bluetoothService.BeginReceiveMessageAsync(); device.Services.Add(bluetoothService); } } if (device.Services.Count == 0) { return(null); } else { return(device); } }