How to open a serial port by friendly name?

后端 未结 8 1928
日久生厌
日久生厌 2020-11-29 02:10

friendly name = the name that appears in \"Device Manager\" under \"Ports (COM & LPT).

EDIT: two solutions provided below. One with WMI and another with SetupAPI

8条回答
  •  长情又很酷
    2020-11-29 02:59

    You might also want to consider using the registry as I have found WMI quite slow (5 or 6 seconds)

    In my case I wanted to identify the COM port name of a device with a known friendly name. Using regedit i searched the registry for the friendly name in a key which also contained the COM port. Because the key I found was some sort of random ID along with 10 others I went up a few levels to find a key suitable to search within.

    The code I came up with is as follows:

    Dim searchFriendlyName = "Your Device Name".ToLower
    Dim k0 = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Enum\USB\", False)
    For Each k1Name In k0.GetSubKeyNames
        Dim k1 = k0.OpenSubKey(k1Name, False)
        For Each k2name In k1.GetSubKeyNames
            Dim k2 = k1.OpenSubKey(k2name, False)
            If k2.GetValueNames.Contains("FriendlyName") AndAlso k2.GetValue("FriendlyName").ToString.ToLower.Contains(searchFriendlyName) Then
                If k2.GetSubKeyNames.Contains("Device Parameters") Then
                    Dim k3 = k2.OpenSubKey("Device Parameters", False)
                    If k3.GetValueNames.Contains("PortName") Then
                        For Each s In SerialPort.GetPortNames
                            If k3.GetValue("PortName").ToString.ToLower = s.ToLower Then
                                Return s
                            End If
                        Next
                    End If
                End If
            End If
        Next
    Next
    

    This will of course need to be modified depending upon how and where your device shows up in the registry but if you are trying to 'Auto Detect' the Com Port of a specific type of deivce then you should be able to make this work.

    Remember if you have to recursivly search lots of keys then this will slow the above solution down so try and find the right place in the registry to look.

    I also included WMI code after the registry search in case the registry search came up empty:

    Dim mg As New System.Management.ManagementClass("Win32_SerialPort")
    Try
    
        For Each i In mg.GetInstances()
            Dim name = i.GetPropertyValue("Name")
            If name IsNot Nothing AndAlso name.ToString.ToLower.Contains(searchFriendlyName.ToLower) Then
                Return i.GetPropertyValue("DeviceId").ToString
            End If
        Next
    Finally
        mg.Dispose()
    End Try
    

提交回复
热议问题