在网上找了很多资料关于Winform如何使用电脑自带蓝牙与设备(手机、仪器、工具、3C电器等等)的低功耗蓝牙(BLE)进行通信的示例,找了很久都没有一个完整的解决方案,最近终于经过自己的不断研究实现了在Winform上实现了与BLE设备的蓝牙通信。
Winform BLE可在Windows 10/11系统下运行。
这里将几个关键点说明下,供大家参考:
1. 准备工作
添加两个引用:
System.Runtime.WindowsRuntime
Windows
路径:
C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETCorev4.5System.Runtime.WindowsRuntime.dll
C:Program Files (x86)Windows Kits10UnionMetadata10.0.19041.0Windows.winmd
2. 工程中添加命名空间
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Security.Cryptography;
using Windows.Storage.Streams;
添加完成后,BluetoothLEDevice,DeviceWatcher,GattCharacteristic这些类就可以使用了。
3. 搜索蓝牙设备
这里推荐使用DeviceWatcher来查找蓝牙
// Query for extra properties you want returned
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.Bluetooth.Le.IsConnectable", "System.Devices.Aep.CanPair", "System.Devices.Aep.IsConnected" };
DeviceWatcher deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromAppearance(BluetoothLEAppearance.FromParts(BluetoothLEAppearanceCategories.Uncategorized, BluetoothLEAppearanceSubcategories.Generic)),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Clear BLE List
// Start the watcher.
deviceWatcher.Start();
4. 连接设备
await BluetoothLEDevice.FromIdAsync(DeviceInformation.Id);
连接状态可通过BluetoothLEDevice.ConnectionStatusChanged事件获得
成功连接状态:(sender.ConnectionStatus == BluetoothConnectionStatus.Connected)
5. 搜索服务和特征值获取
在连接设备后即可进行服务搜索:
BluetoothLEDevice.GetGattServicesAsync().Completed = async (asyncInfo, asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Completed)
{
var services = asyncInfo.GetResults().Services;
if (services?.Count > 0)
{
foreach (GattDeviceService serv in services)
{
GattCharacteristicsResult result = await serv.GetCharacteristicsAsync();
foreach (GattCharacteristic gc in result.Characteristics)
{
//获取到characteristics先存储起来
}
}
}
//选择蓝牙通信characteristics使用的特征值
}
};
6. 读写数据通信
如果characteristics具备Notify特性,可以使用事件通知方式获取接受数据
Characteristic.ValueChanged += BleCom_NotifyCharacteristic_ValueChanged;
使用:
byte[] dataBuf;
CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out dataBuf);
的方式取出接收到的数据。
使用:
Characteristic.WriteValueAsync
发送数据。
至此,Winform BLE蓝牙通信即可实现!
示例:
示例工程截图:
说明:该Demo Exe程序CSDN链接:BLE_Demo(WinForm).rar-C#文档类资源-CSDN文库



