C# 用windows11API 实现HID蓝牙键盘的链接、数据读取
时间: 2024-03-11 12:47:30 浏览: 257
好的,下面是一个简单的 C# 示例代码,使用Windows 11 API 实现HID蓝牙键盘的链接、数据读取:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
namespace BluetoothHIDKeyboardDemo
{
class Program
{
static async Task Main(string[] args)
{
// 获取蓝牙键盘设备
DeviceInformationCollection deviceInfoList = await DeviceInformation.FindAllAsync(
GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HumanInterfaceDevice));
if (deviceInfoList.Count == 0)
{
Console.WriteLine("未找到蓝牙键盘设备!");
return;
}
// 连接第一个设备
BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(deviceInfoList[0].Id);
if (bleDevice == null)
{
Console.WriteLine("连接设备失败!");
return;
}
// 获取HID服务
GattDeviceService hidService = bleDevice.GetGattService(GattServiceUuids.HumanInterfaceDevice);
if (hidService == null)
{
Console.WriteLine("未找到HID服务!");
return;
}
// 获取输入报告特征
GattCharacteristic inputReportCharacteristic = hidService.GetCharacteristics(
GattCharacteristicUuids.HidInputReport)[0];
if (inputReportCharacteristic == null)
{
Console.WriteLine("未找到输入报告特征!");
return;
}
// 订阅输入报告特征的通知
inputReportCharacteristic.ValueChanged += InputReportCharacteristic_ValueChanged;
await inputReportCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
Console.WriteLine("蓝牙键盘已连接,等待输入...");
Console.ReadLine();
}
private static void InputReportCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
// 读取输入报告数据
byte[] data = new byte[args.CharacteristicValue.Length];
Windows.Storage.Streams.DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(data);
// 处理输入报告数据
Console.Write(Encoding.ASCII.GetString(data));
}
}
}
```
请注意,这只是一个示例代码,您需要根据自己的具体需求进行修改和完善。此外,您需要确保您的设备已经启用了蓝牙和 HIDProfile,并已经配对了蓝牙键盘。
阅读全文