如何在桌面.NET应用程序中获得BLE广告回调?

我试图从.NET Windows桌面应用程序获取BLE广告回调。 我能够调用API,但是从未在WPF或命令行应用程序中从OS调用Received事件。 当从VS2015中的unit testing或通用Windows应用程序调用代码时,我确实得到了事件。 但是,我需要做其他通用Windows中没有的东西。 这是代码:

using Windows.Devices.Bluetooth.Advertisement; public static void ScanForAdvertisments() { mWatcher = new BluetoothLEAdvertisementWatcher(); mWatcher.Received += OnAdvertismentReceived; mWatcher.ScanningMode = BluetoothLEScanningMode.Active; mWatcher.Start(); } public static void OnAdvertismentReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { ulong address = args.BluetoothAddress; short rssi = args.RawSignalStrengthInDBm; } 
  • 我引用了Windows.winmd以包含BLE / UWP名称空间。
  • 我在Windows 10周年纪念版上使用框架版本4.6.1,我在之前的Windows版本中也遇到了同样的问题。
  • 使用UWP应用程序我在appxmanifest中为蓝牙设置了DeviceCapability。 unit testing项目似乎不需要这个,我不知道如何将appxmanifests应用于桌面项目。
  • status属性报告扫描程序正在运行,并且也永远不会触发已停止的事件。

无论如何,这是一个Windows错误吗? 有办法解决它吗? 我试着研究应用程序服务,但似乎没有设置好很好地调用桌面代码,从UWP调用桌面代码似乎很难部署。 谢谢。

刚刚使用Console .NET 4.6.1应用程序尝试了这一点,广告回调正在通过。 我之前写了一篇GitHub示例 ,这可能有所帮助。 他们获得WinRT API工作的关键是两个参考:

要使用WinRT API,请添加两个引用:

  1. C:\ Program Files(x86)\ Windows Kits \ 10 \ UnionMetadata \ Windows.winmd

  2. C:\ Program Files(x86)\ Reference Assemblies \ Microsoft \ Framework.NETCore \ v4.5 \ System.Runtime.WindowsRuntime.dll

听起来你可能错过了第二个参考。 我能够将v4.5 .NetCore框架与4.6.1一起使用。