Unable to Discover Bluetooth Devices in UWP application but works in WPF application

397 Views Asked by At

I am trying scan the Bluetooth devices using 32feet.NET library using the following code.

private void Button_Click(object sender, RoutedEventArgs e)
{
    BluetoothClient client = new BluetoothClient();
    foreach (BluetoothDeviceInfo bdi in client.DiscoverDevices())
    {
        System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress);
    }
}

The above code returns list of available Bluetooth devices in WPF application. But when I use the same code in UWP application I am getting the following exception.

System.Runtime.InteropServices.COMException: 'A method was called at an unexpected time.

When I tried to use the async/await as per the suggestion given here to fix this exception, I am not able to use async/await in collections. So I used Task.FromResult method as below then also the exception is not fixed.

private async void Button_Click(object sender, RoutedEventArgs e)
{
    BluetoothClient client = new BluetoothClient();
    var dev = await Task.FromResult(client.DiscoverDevices());
            
    foreach (BluetoothDeviceInfo bdi in dev)
    {
      System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress);
    }
 }

Can someone help me why the same code works in WPF application but not in UWP application?

2

There are 2 best solutions below

0
On

Unable to Discover Bluetooth Devices in UWP application but works in WPF application

I'm afraid the third part library does not support UWP platform, if you want to discover Bluetooth device in UWP platform, we suggest you use DeviceWatcher class to enumerate all Bluetooth device.

Here is official code sample that you could refer and here is official document.

0
On

UWP applications are containerised (sandboxed). This means that UWP applications cannot communicate with the kernel and other parts of the operating system directly. The only way a UWP application can communicate with the operating system is through Windows 10/11 API calls.
Example: await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings"));

There exist a couple of workarounds, one notable example is to download the UWP SDK in a WPF application and use UWP libraries within that respective WPF application.

Look here: https://www.thomasclaudiushuber.com/2019/04/26/calling-windows-10-apis-from-your-wpf-application/