要在Windows上使用C#操作蓝牙,您需要使用Windows的蓝牙API。这通常涉及到使用Windows.Devices.Bluetooth命名空间中的类。以下是一个基本的示例,演示了如何扫描附近的蓝牙设备。

 

请注意,要使用此代码,您需要确保您的开发环境符合Windows的最低要求,并正确引用所需的程序集。

 

首先,您需要在项目中添加对Windows.Devices.Bluetooth的引用。在Visual Studio中,可以通过NuGet包管理器安装Windows.Devices.Bluetooth包。

 

下面是一个简单的C#代码示例,用于扫描附近的蓝牙设备:

 

csharp

复制

using System;

using Windows.Devices.Bluetooth;

using Windows.Devices.Enumeration;

using Windows.Foundation;

using Windows.UI.Core;

namespace BluetoothScannerApp

{

    public class BluetoothScanner

    {

        // 回调用于处理发现设备的异步操作

        private readonly DeviceRequestedArgs _deviceRequestedArgs = new DeviceRequestedArgs();

        private readonly Action _foundDeviceCallback;

        private readonly CancellationTokenSource _cancellationSource = new CancellationTokenSource();

        private readonly DispatcherTimer _timer = new DispatcherTimer();

        public BluetoothScanner(Action foundDeviceCallback)

        {

            _foundDeviceCallback = foundDeviceCallback;

            _timer.Interval = TimeSpan.FromSeconds(1); // 设置扫描间隔为1秒

            _timer.Tick += Timer_Tick; // 添加计时器tick事件处理程序

        }

        public void StartScanning()

        {

            // 请求发现设备权限,如果未授权则请求授权

            var deviceDiscoveryManager = DeviceDiscoveryManager.CreateForBluetoothRadio();

            var deviceSelector = DeviceClass.HumanInterfaceDevice + " AND NOT VendorId: 0x0000"; // 选择非系统默认的蓝牙设备

            _deviceRequestedArgs.Request = deviceDiscoveryManager.CreateDeviceInformationListAsync(deviceSelector).AsTask(CancellationToken.None);

            _deviceRequestedArgs.Request.ContinueWith(t => // 确保设备请求成功后再启动扫描

            {

                if (!t.IsCanceled)

                {

                    _deviceRequestedArgs.Request.GetResults(); // 获取设备列表,即使失败也会触发回调函数

                    _timer.Start(); // 启动计时器开始扫描

                }

            });

        }

        private void Timer_Tick(object sender, object e)

        {

            if (_deviceRequestedArgs != null) // 确保有设备请求上下文

            {

                if (_deviceRequestedArgs.Request != null && !_deviceRequestedArgs.Request.IsCompleted) // 确保设备请求未完成时继续扫描

                {

                    return; // 避免重复扫描相同的设备信息列表结果,避免造成无限循环

                }

                _timer.Stop(); // 停止扫描以避免重复触发回调函数或出现延迟情况下的扫描操作。

                var deviceInfoList = _deviceRequestedArgs.Request?.Result; // 获取设备信息列表(可能为空)

                if (deviceInfoList != null) // 如果获取到设备信息列表则进行处理。

                {

                    foreach (var deviceInfo in deviceInfoList) // 遍历每个设备信息对象。

                    {

                        var device = deviceInfo.GetDevice(); // 获取BluetoothDevice对象以便进行交互。

                        _foundDeviceCallback?.Invoke(device); // 调用传入的回调函数以通知找到了设备。

                    }

                }

                else // 如果未能获取到设备信息列表则进行错误处理。

                {

                    // 处理错误情况,例如显示错误消息或进行日志记录等。

                }

            }

            else // 如果设备请求上下文为空则进行错误处理。

            {

                // 处理错误情况,例如显示错误消息或进行日志记录等。

            }

        }

    }

}

 

参考阅读

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。