本文转自:
https://www.cnblogs.com/webtojs/p/9675956.html
winform 程序调用Windows.Devices.Bluetoot API 实现windows下BLE蓝牙设备自动连接,收发数据功能。不需要使用win10的UWP开发。
先贴图,回头来完善代码
源码如下:
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Security.Cryptography;
namespace BLECode
public class BluetoothLECode
//存储检测的设备MAC。
public string CurrentDeviceMAC { get; set; }
//存储检测到的设备。
public BluetoothLEDevice CurrentDevice { get; set; }
//存储检测到的主服务。
public GattDeviceService CurrentService { get; set; }
//存储检测到的写特征对象。
public GattCharacteristic CurrentWriteCharacteristic { get; set; }
//存储检测到的通知特征对象。
public GattCharacteristic CurrentNotifyCharacteristic { get; set; }
public string ServiceGuid { get; set; }
public string WriteCharacteristicGuid { get; set; }
public string NotifyCharacteristicGuid { get; set; }
private const int CHARACTERISTIC_INDEX = 0;
//特性通知类型通知启用
private const GattClientCharacteristicConfigurationDescriptorValue CHARACTERISTIC_NOTIFICATION_TYPE = GattClientCharacteristicConfigurationDescriptorValue.Notify;
private Boolean asyncLock = false;
private DeviceWatcher deviceWatcher;
//定义一个委托
public delegate void eventRun(MsgType type, string str,byte[] data=null);
//定义一个事件
public event eventRun ValueChanged;
public BluetoothLECode(string serviceGuid, string writeCharacteristicGuid, string notifyCharacteristicGuid)
ServiceGuid = serviceGuid;
WriteCharacteristicGuid = writeCharacteristicGuid;
NotifyCharacteristicGuid = notifyCharacteristicGuid;
public void StartBleDeviceWatcher()
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" };
string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
deviceWatcher =
DeviceInformation.CreateWatcher(
aqsAllBluetoothLEDevices,
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
deviceWatcher.Start();
string msg = "自动发现设备中..";
ValueChanged(MsgType.NotifyTxt, msg);
private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
string msg = "自动发现设备停止";
ValueChanged(MsgType.NotifyTxt, msg);
private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
ValueChanged(MsgType.NotifyTxt, "发现设备:" + args.Id);
if (args.Id.EndsWith(CurrentDeviceMAC))
Matching(args.Id);
/// <summary>
/// 按MAC地址查找系统中配对设备
/// </summary>
/// <param name="MAC"></param>
public async Task SelectDevice(string MAC)
CurrentDeviceMAC = MAC;
CurrentDevice = null;
DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()).Completed = async (asyncInfo, asyncStatus) =>
if (asyncStatus == AsyncStatus.Completed)
DeviceInformationCollection deviceInformation = asyncInfo.GetResults();
foreach (DeviceInformation di in deviceInformation)
await Matching(di.Id);
if (CurrentDevice == null)
string msg = "没有发现设备";
ValueChanged(MsgType.NotifyTxt, msg);
StartBleDeviceWatcher();
/// <summary>
/// 按MAC地址直接组装设备ID查找设备
/// </summary>
/// <param name="MAC"></param>
/// <returns></returns>
public async Task SelectDeviceFromIdAsync(string MAC)
CurrentDeviceMAC = MAC;
CurrentDevice = null;
BluetoothAdapter.GetDefaultAsync().Completed = async (asyncInfo, asyncStatus) =>
if (asyncStatus == AsyncStatus.Completed)
BluetoothAdapter mBluetoothAdapter = asyncInfo.GetResults();
byte[] _Bytes1 = BitConverter.GetBytes(mBluetoothAdapter.BluetoothAddress);//ulong转换为byte数组
Array.Reverse(_Bytes1);
string macAddress = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
string Id = "BluetoothLE#BluetoothLE" + macAddress + "-" + MAC;
await Matching(Id);
private async Task Matching(string Id)
BluetoothLEDevice.FromIdAsync(Id).Completed = async (asyncInfo, asyncStatus) =>
if (asyncStatus == AsyncStatus.Completed)
BluetoothLEDevice bleDevice = asyncInfo.GetResults();
//在当前设备变量中保存检测到的设备。
CurrentDevice = bleDevice;
await Connect();
catch (Exception e)
string msg = "没有发现设备" + e.ToString();
ValueChanged(MsgType.NotifyTxt, msg);
StartBleDeviceWatcher();
private async Task Connect()
string msg = "正在连接设备<" + CurrentDeviceMAC + ">..";
ValueChanged(MsgType.NotifyTxt, msg);
CurrentDevice.ConnectionStatusChanged += CurrentDevice_ConnectionStatusChanged;
await SelectDeviceService();
/// <summary>
/// 主动断开连接
/// </summary>
/// <returns></returns>
public void Dispose()
CurrentDeviceMAC = null;
CurrentService?.Dispose();
CurrentDevice?.Dispose();
CurrentDevice = null;
CurrentService = null;
CurrentWriteCharacteristic = null;
CurrentNotifyCharacteristic = null;
ValueChanged(MsgType.NotifyTxt, "主动断开连接");
private void CurrentDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected && CurrentDeviceMAC != null)
string msg = "设备已断开,自动重连";
ValueChanged(MsgType.NotifyTxt, msg);
if (!asyncLock)
asyncLock = true;
CurrentDevice.Dispose();
CurrentDevice = null;
CurrentService = null;
CurrentWriteCharacteristic = null;
CurrentNotifyCharacteristic = null;
SelectDeviceFromIdAsync(CurrentDeviceMAC);
string msg = "设备已连接";
ValueChanged(MsgType.NotifyTxt, msg);
/// <summary>
/// 按GUID 查找主服务
/// </summary>
/// <param name="characteristic">GUID 字符串</param>
/// <returns></returns>
public async Task SelectDeviceService()
Guid guid = new Guid(ServiceGuid);
CurrentDevice.GetGattServicesForUuidAsync(guid).Completed = (asyncInfo, asyncStatus) =>
if (asyncStatus == AsyncStatus.Completed)
GattDeviceServicesResult result = asyncInfo.GetResults();
string msg = "主服务=" + CurrentDevice.ConnectionStatus;
ValueChanged(MsgType.NotifyTxt, msg);
if (result.Services.Count > 0)
CurrentService = result.Services[CHARACTERISTIC_INDEX];
if (CurrentService != null)
asyncLock = true;
GetCurrentWriteCharacteristic();
GetCurrentNotifyCharacteristic();
msg = "没有发现服务,自动重试中";
ValueChanged(MsgType.NotifyTxt, msg);
SelectDeviceService();
catch (Exception e)
ValueChanged(MsgType.NotifyTxt, "没有发现服务,自动重试中");
SelectDeviceService();
/// <summary>
/// 设置写特征对象。
/// </summary>
/// <returns></returns>
public async Task GetCurrentWriteCharacteristic()
string msg = "";
Guid guid = new Guid(WriteCharacteristicGuid);
CurrentService.GetCharacteristicsForUuidAsync(guid).Completed = async (asyncInfo, asyncStatus) =>
if (asyncStatus == AsyncStatus.Completed)
GattCharacteristicsResult result = asyncInfo.GetResults();
msg = "特征对象=" + CurrentDevice.ConnectionStatus;
ValueChanged(MsgType.NotifyTxt, msg);
if (result.Characteristics.Count > 0)
CurrentWriteCharacteristic = result.Characteristics[CHARACTERISTIC_INDEX];
msg = "没有发现特征对象,自动重试中";
ValueChanged(MsgType.NotifyTxt, msg);
await GetCurrentWriteCharacteristic();
if (CurrentWriteCharacteristic != null)
CurrentWriteCharacteristic.WriteValueAsync(CryptographicBuffer.CreateFromByteArray(data), GattWriteOption.WriteWithResponse);
/// <summary>
/// 设置通知特征对象。
/// </summary>
/// <returns></returns>
public async Task GetCurrentNotifyCharacteristic()
string msg = "";
Guid guid = new Guid(NotifyCharacteristicGuid);
CurrentService.GetCharacteristicsForUuidAsync(guid).Completed = async (asyncInfo, asyncStatus) =>
if (asyncStatus == AsyncStatus.Completed)
GattCharacteristicsResult result = asyncInfo.GetResults();
msg = "特征对象=" + CurrentDevice.ConnectionStatus;
ValueChanged(MsgType.NotifyTxt, msg);
if (result.Characteristics.Count > 0)
CurrentNotifyCharacteristic = result.Characteristics[CHARACTERISTIC_INDEX];
CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
await EnableNotifications(CurrentNotifyCharacteristic);
msg = "没有发现特征对象,自动重试中";
ValueChanged(MsgType.NotifyTxt, msg);
await GetCurrentNotifyCharacteristic();
/// <summary>
/// 设置特征对象为接收通知对象
/// </summary>
/// <param name="characteristic"></param>
/// <returns></returns>
public async Task EnableNotifications(GattCharacteristic characteristic)
string msg = "收通知对象=" + CurrentDevice.ConnectionStatus;
ValueChanged(MsgType.NotifyTxt, msg);
characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CHARACTERISTIC_NOTIFICATION_TYPE).Completed = async (asyncInfo, asyncStatus) =>
if (asyncStatus == AsyncStatus.Completed)
GattCommunicationStatus status = asyncInfo.GetResults();
if (status == GattCommunicationStatus.Unreachable)
msg = "设备不可用";
ValueChanged(MsgType.NotifyTxt, msg);
if (CurrentNotifyCharacteristic != null && !asyncLock)
await EnableNotifications(CurrentNotifyCharacteristic);
asyncLock = false;
msg = "设备连接状态" + status;
ValueChanged(MsgType.NotifyTxt, msg);
private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
byte[] data;
CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data);
string str = BitConverter.ToString(data);
ValueChanged(MsgType.BLEData,str, data);
public enum MsgType
NotifyTxt,
BLEData
调用方式:
bluetooth = new BluetoothLECode(_serviceGuid, _writeCharacteristicGuid, _notifyCharacteristicGuid);
bluetooth.ValueChanged += Bluetooth_ValueChanged;
如果你无法编译上面的类库,请直接使用我生成的DLL文件
https://files.cnblogs.com/files/webtojs/BLECode.rar
本文转自:https://www.cnblogs.com/webtojs/p/9675956.htmlwinform 程序调用Windows.Devices.Bluetoot API 实现windows下BLE蓝牙设备自动连接,收发数据功能。不需要使用win10的UWP开发。先贴图,回头来完善代码 源码如下:using System;using System...
在网上找了很多资料关于
Winform
如何试用电脑自带
蓝牙
与设备(手机、仪器、工具、3C电器等等)的低功耗
蓝牙
(
BLE
)进行通信的示例,找了很久都没有一个完整的解决方案,最近终于经过自己的不断研究实现了在
Winform
上实现了与
BLE
设备的
蓝牙
通信。
这里将几个关键点说明下,供大家参考:
winform
程序调用
Windows
.Devices.Bluetoot API 实现
windows
下
BLE
蓝牙
设备自动
连接
,收发数据功能。不需要使用win10的UWP开发。
实际例子用vs2022编写,可直接编译运行
现在很多电脑提供了
蓝牙
支持,很多笔记本网卡也集成了
蓝牙
功能,也可以采用USB
蓝牙
方便的
连接
手机等
蓝牙
设备进行通信。
操作
蓝牙
要使用类库InTheHand.Net.Personal
首先在项目中引用该类库;
static void Main(string[] args)
BluetoothRadio bluetoothRadio = BluetoothRadio.PrimaryRadio;
if (bluetoothRadio == null)
Console.WriteLine(没有找到本机
蓝牙
设备!);
Console.Writ
这是
蓝牙
4.0
模块(
蓝牙
4.0
从模块)。与
蓝牙
版本2.0和3.0相比,它的功耗更低,更先进。您可以使用此模块轻松地将自己的项目
连接
到Bluetooth
4.0
的主设备。例如,它可以将检测到的与您身体信息有关的数据传输到手机上进行显示或分析,然后帮助您更好地管理您的身体状况。
蓝牙
4.0
模块
PIN:0000
默认波特率:38400
尺寸:25.43mm x 20.35mm
该演示将向您展示如何将
蓝牙
设备与Xadow
BLE
Slave
连接
并进行通信。您可以使用它与手机通信(使用
蓝牙
4.0
)。现在让我们进行测试: - 将Xadow
BLE
Slave
连接
到Xadow主板,并使用USB电缆将主板
连接
到PC。在正常模式下,蓝色LED将一次闪烁一次。如果蓝色LED指示灯熄灭,请单击Xadow主板上的“重置”按钮。
准备好您的手机设备并安装“BlueSPP”APP并启动BlueSPP。请记住,您的设备应该是
蓝牙
4.0
。
最近,随着智能穿戴式设备、智能医疗以及智能家居的普及,
蓝牙
开发在移动开中显得非常的重要。由于公司需要,研究了一下,
蓝牙
4.0
在Android中的应用。
以下是我的一些总结。
1.先介绍一下关于
蓝牙
4.0
中的一些名词吧:
(1)、GATT(Gneric Attibute Profile)
通过
ble
连接
,读写属性类小数据Profile通用的规范。现在所有的
ble
应用Profile 都是基于GATT
(2)、ATT(Attribute Protocal)
GATT是基于ATT Potocal的ATT针对
BLE
设备专门做的具体就是传输过程中使用尽量少的数据,每个属性都有个唯一的UUID,属性ch
蓝牙
BLE
WinForm
示例程序(可执行文件),使用HC-42低功耗
蓝牙
模块
BLE
5.0
连接
成功,且收发数据正常,可用于简单的
BLE
蓝牙
调试,支持Hex和字符串类型数据收发。
Winform
BLE
设计要点请查看我的博客相关链接:
https://blog.csdn.net/qingfeng_hero/article/details/120995069
为了便携,买了个小米无线鼠标。有两种模式,一种是插无线收发器,一种是
蓝牙
。插收发器倒是没任何问题,但是占一个USB口总是不爽。
蓝牙
模式很奇怪,在家里的Win10电脑可以连,但是办公用的Win7电脑就是搜不到鼠标。
查了很多资料,主要有几种说法:
1、说电脑没有
蓝牙
的、
蓝牙
模块不是
4.0
的、硬件不支持什么的:纯是自说自话。
2、还有说Win7就是不支持,Win8以上才支持
蓝牙
4.0
:接近真相了,但原因还是不准确。
3、
蓝牙
4.0
采用
BLE
技术(Bluetooth Low Energy
蓝牙
低能耗技术),但是其驱动程序没有包括在Win7系统内,而是从Win8开始带有
BLE
驱动:真相在此。
蓝牙
4.0
BLE
(低耗
蓝牙
)完全开发手册是一本详细介绍
蓝牙
4.0
BLE
技术以及其开发的书籍。该手册提供了全面的信息,帮助开发者理解和运用
蓝牙
4.0
BLE
技术。
在
蓝牙
4.0
BLE
完全开发手册中,首先会对
蓝牙
技术做简要介绍,包括其发展历史、应用领域和主要特点。接下来会详细讲解
蓝牙
4.0
BLE
的原理和架构,以及与传统
蓝牙
的区别和优势。
然后,手册会深入介绍
蓝牙
4.0
BLE
的开发过程。首先是硬件方面,讲解了
蓝牙
4.0
BLE
芯片的选择和使用,以及与其他硬件模块的接口和
连接
。
接着,手册会详细介绍
蓝牙
4.0
BLE
的软件开发。从
蓝牙
协议栈的架构和功能开始,包括扫描、
连接
、传输和配置等。随后,会讲解关于
蓝牙
4.0
BLE
的数据传输和安全性的技术细节,如数据格式、特征值和服务的定义等。
在软件开发的过程中,手册还会介绍一些常见的开发工具和开发环境,包括
蓝牙
4.0
BLE
开发板、调试工具和开发软件的配置和操作。
最后,手册还会提供一些实际案例和应用示例,以便开发者更好地理解和运用
蓝牙
4.0
BLE
技术。同时,手册也会介绍一些开发中的常见问题和解决方法,以及软件和硬件的调试技巧和注意事项。
总之,
蓝牙
4.0
BLE
完全开发手册是一本全面而实用的参考书,适合对
蓝牙
4.0
BLE
技术感兴趣的开发者和工程师,能够帮助他们深入理解
蓝牙
4.0
BLE
技术,掌握开发过程中的关键技术和实践经验。