VB GetObject() hands if Bluetooth printer port paired but off or out of range
Issue: VB GetObject() hangs if Bluetooth printer paired but off or out of range
Win10
Visual Studio 2005 net 2 or
Visual Studio 2019 (latest update) net 4
Visual Basic
I am using the following code to find the USB serial port for an attached device based on PID and VID.
For Each objItem In GetObject("winmgmts:\.\root\cimv2").ExecQuery("Select * from Win32_SerialPort")
If InStr(objItem.PNPDeviceID, "VID_04D8&" & pid) <> 0 Then
FoundComPort = objItem.DeviceID
Exit For
End If
Next
The code works perfectly without a Bluetooth printer installed.
When a Bluetooth printer is installed and paired, it creates two COM ports as seen in device manager.
Note: If you try to remove the above, it will let you but next time you check Device Manager, they are automatically put back in. To remove a Bluetooth Printer, you must go into Win Settings, Bluetooth and remove the device from there.
1) When the Bluetooth printer is installed, paired and ON, the code works but is slow to respond.
2) When the Bluetooth printer is installed, paired but OFF or out of range, the GetObject() code hangs.
I assume the reason it hangs is due to the two visible ports showing up in the list of COM ports. For the unresponsive port (COM6) in my case, GetObject() is unable to retrieve the PID or VID.
Similarly for the other port (COM15), when the printer is OFF, no PID or VID info is returned and the GetObject() function hangs i.e. does not handle the error properly.
QUESTION
Other than forcing the client to uninstall and re-install Bluetooth printers each time they want to run the application, is there a better alternative to GetObject() or another way to finding which COM port a device with a specific PID and VID is attached to that is more Bluetooth Printer friendly?
Thanks,
Ken