c++ winrt BluetoothLEDevice::FromIdAsync() 结果导致访问被拒绝

问题描述 投票:0回答:1

我正在尝试编写一个 C++ winrt 应用程序来连接到蓝牙 LE 设备,类似于 Microsoft 的 BluetoothLE 示例。在示例中,我可以连接到蓝牙设备。但是,当我尝试使用相同的代码创建新的 C++ winrt 应用程序时,我收到异常:80070005 访问被拒绝。

在这两个应用程序中,我在 MainPage.xaml 中放置了一个按钮,并将以下代码添加到 MainPage.cpp 文件中:

fire_and_forget MainPage::ClickHandler(IInspectable const&, RoutedEventArgs const&)
{
Windows::Devices::Bluetooth::BluetoothLEDevice bluetoothLeDevice2{ nullptr };

        try {
         
            bluetoothLeDevice2 = co_await Windows::Devices::Bluetooth::BluetoothLEDevice::FromIdAsync(L"BluetoothLE#BluetoothLEd4:3b:04:bc:61:d1-88:33:14:d9:5b:88");
    
            if (bluetoothLeDevice2 == nullptr)
            {
                LogOnConsole(L"No connection.");
            }
        }
        catch (hresult_error & ex)
        {
            if (ex.to_abi() == HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE))
            {
                LogOnConsole(L"Bluetooth radio is not on.");
            }
            else
            {
                throw;
            }
        }

}

在 Microsoft 的示例中它可以工作,但在我自己的应用程序中 bluetoothLeDevice2 是 nullptr。

我比较了这两个应用程序,并注意到我的应用程序使用更新的 winrt 库,但我不知道如何修复我的代码。

bluetooth-lowenergy windows-runtime c++-winrt
1个回答
0
投票

UWP运行在沙箱中,如果你想在UWP中使用蓝牙,你需要在Package.appxmanifest中声明蓝牙功能。

<Capabilities> <DeviceCapability Name="bluetooth" /> </Capabilities>
© www.soinside.com 2019 - 2024. All rights reserved.