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

How do you get a BLE Advertisment callback in a desktop .NET app?

我正在尝试从 .NET Windows 桌面应用程序获取 BLE 广告回调。我能够调用 API,但是 Received 事件永远不会从 WPF 或命令行应用程序中的 OS 调用。当从 VS2015 中的单元测试或通用 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 错误吗?有没有办法解决它?我尝试查看应用程序服务,但它们似乎没有设置为很好地调用桌面代码,并且从 UWP 调用桌面代码似乎部署起来很复杂。谢谢

刚刚使用 Console .NET 4.6.1 应用程序对此进行了尝试,广告回调正在通过。我之前写了一个 GitHub Sample ,这可能会有所帮助。使 WinRT API 正常工作的关键是两个参考:

To use the WinRT APIs, add two references:

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

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

听起来您可能遗漏了第二个参考。我能够在 4.6.1 中使用 v4.5 .NetCore 框架。