C# Windows 11 提供的 Bluetooth API实现蓝牙的扫描例程
时间: 2024-03-06 22:48:14 浏览: 197
PID.rar_matlab例程_C#_
5星 · 资源好评率100%
以下是一个简单的 C# Windows 11 示例代码,演示如何使用 BluetoothLEAdvertisementWatcher 类来扫描周围的蓝牙设备:
```csharp
using System;
using System.Collections.Generic;
using Windows.Devices.Bluetooth.Advertisement;
class Program
{
static BluetoothLEAdvertisementWatcher watcher;
static List<string> discoveredDevices = new List<string>();
static void Main(string[] args)
{
// 创建 BluetoothLEAdvertisementWatcher 并设置扫描参数
watcher = new BluetoothLEAdvertisementWatcher();
watcher.ScanningMode = BluetoothLEScanningMode.Active;
watcher.SignalStrengthFilter.InRangeThresholdInDBm = -70;
watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -75;
watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromSeconds(2);
// 添加事件处理程序
watcher.Received += Watcher_Received;
watcher.Stopped += Watcher_Stopped;
// 启动扫描
watcher.Start();
Console.WriteLine("Scanning for Bluetooth devices. Press any key to stop.");
Console.ReadKey();
// 停止扫描
watcher.Stop();
// 输出扫描结果
Console.WriteLine("Discovered devices:");
foreach (string device in discoveredDevices)
{
Console.WriteLine(device);
}
}
private static void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
string deviceName = args.Advertisement.LocalName;
string deviceId = args.BluetoothAddress.ToString("X");
if (!discoveredDevices.Contains(deviceName))
{
discoveredDevices.Add(deviceName);
Console.WriteLine($"Discovered device: {deviceName} ({deviceId})");
}
}
private static void Watcher_Stopped(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementWatcherStoppedEventArgs args)
{
Console.WriteLine("Bluetooth LE watcher stopped.");
}
}
```
此代码创建一个 BluetoothLEAdvertisementWatcher,设置扫描参数,添加事件处理程序,并启动扫描。当扫描到新设备时,它将输出设备名称和 ID,然后将其添加到 discoveredDevices 列表中。当用户按下任何键时,它将停止扫描并输出已发现的设备列表。
阅读全文