You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB调用BluetoothLEDevice.FromIdAsync返回无法转换的__ComObject问题咨询

问题原因

你当前拿到的System.__ComObject是WinRT异步操作IAsyncOperation<BluetoothLEDevice>的COM包装对象,并非实际的蓝牙设备实例。BluetoothLEDevice.FromIdAsync是异步API,直接调用时返回的是异步操作对象,你需要等待操作完成才能拿到最终的BluetoothLEDevice实例,C++示例可以直接赋值是因为示例代码中已经做了异步等待处理,并非不需要转换。

解决方案

方案1:使用Await异步等待(推荐)

这是WinRT异步API的标准调用方式,仅需对你的代码做两处修改:

  1. 给方法添加Async修饰符
  2. 调用BluetoothLEDevice.FromIdAsync时添加Await关键字
    修改后代码如下:
Private Async Sub ConnectToDevice(di As DeviceInformation)
    '
    ' di.id = "BluetoothLE#BluetoothLE48:5f:99:3c:fd:36-84:2e:14:26:9e:7b"
    '
    Debug.Print("Connecting To " & di.Name & " at " & Now.ToShortTimeString)
    Dim myDevice As BluetoothLEDevice
    Try
        ' 等待异步操作完成,直接获取蓝牙设备实例
        myDevice = Await BluetoothLEDevice.FromIdAsync(di.Id)
    Catch ex As Exception
        Debug.Print(ex.Message)
        Exit Sub
    End Try
    
    ' 后续可正常操作myDevice对象
    If myDevice IsNot Nothing Then
        Debug.Print("设备连接成功:" & myDevice.Name)
    End If
End Sub

方案2:同步获取结果(适用于不支持Async/Await的老项目)

如果你的项目使用的VB版本不支持Async/Await,可以直接调用异步操作的GetResults方法拿到最终结果,注意该方法会阻塞当前线程,不要在UI线程调用避免界面死锁:

Private Sub ConnectToDevice(di As DeviceInformation)
    Debug.Print("Connecting To " & di.Name & " at " & Now.ToShortTimeString)
    Dim myDevice As BluetoothLEDevice
    Try
        ' 同步等待异步操作完成并获取结果
        myDevice = BluetoothLEDevice.FromIdAsync(di.Id).GetResults()
    Catch ex As Exception
        Debug.Print(ex.Message)
        Exit Sub
    End Try
    
    If myDevice IsNot Nothing Then
        Debug.Print("设备连接成功:" & myDevice.Name)
    End If
End Sub

前置检查项

请先确认你的项目满足以下配置要求,否则依然可能出现调用异常:

  • .NET Framework项目:已安装对应版本的Microsoft.Windows.SDK.Contracts NuGet包,目标Windows版本最低为1809
  • .NET 6+项目:项目文件中目标框架已配置为带Windows版本后缀的形式,例如<TargetFramework>net7.0-windows10.0.19041.0</TargetFramework>
  • 项目已声明蓝牙权限,打包应用需在Package.appxmanifest中添加bluetooth、bluetooth.le权限声明,未打包桌面应用需在app.manifest中添加对应权限。

内容的提问来源于stack exchange,提问作者Karl Sangree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 19:06:02