在我們開始之前:在研究這個問題時,我查看了這里和其他地方的數十篇文章,并意識到 VB對藍牙編程來說是最糟糕的。但是,這是針對擁有大量遺留 VB 系統的客戶而我別無選擇。
根據 MS 檔案,BluetoothLEDevice.FromIdAsync它應該回傳一個 BluetoothLEDevice 物件,但在我的系統上它回傳一個System.__ComObject我無法轉換為 BluetoothLEDevice的泛型。我嘗試過 Cast 和 DirectCast,但都不起作用。我看過的示例 C 代碼不需要任何型別的轉換;變數是使用BluetoothLEDevice.FromIdAsync函式宣告和設定的,沒有任何戲劇性。
這是我的測驗代碼。
Private 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 genericObject As Object
Dim myDevice As BluetoothLEDevice
Try
genericObject = BluetoothLEDevice.FromIdAsync(di.Id)
Catch ex As Exception
Debug.Print(ex.Message)
End Try
If Not IsNothing(genericObject) Then Debug.Print("Using 'Object' yeilds " & genericObject.ToString)
Try
myDevice = BluetoothLEDevice.FromIdAsync(di.Id)
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Sub
這是輸出:
Connecting To TM-2021090161 at 2:08 PM
Using 'Object' yeilds System.__ComObject
Exception thrown: 'System.InvalidCastException' in testBTLE.exe
Unable to cast object of type 'System.__ComObject' to type 'Windows.Devices.Bluetooth.BluetoothLEDevice'.
以及回傳的 genericObject 的螢屏截圖:

uj5u.com熱心網友回復:
FromIdAsync 需要異步運行,我不能這樣做,因為我收到一個錯誤,指出它沒有等待者。事實證明,我需要 NuGet System.Runtime.Windowsruntime dll。我添加了 Await,現在它正在作業。
感謝安德魯為我指明了正確的方向。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/378922.html
上一篇:從SQLServer讀取影像時出現“System.OutOfMemoryException:'Outofmemory.'”
