Hey community,

how can i show the connected USB-Device like keyboard, mouse, webcam and so on?
Or how can i search in the connected USB-Devices, if I know the name or only a part of the name?
I am looking for some examples since 2 days, but no one doesn´t work. So I hope you can help me with some code examples in vb.net.

best regards
joshi

Click Here
You should add a reference to System.Management dll

    Function DetectDevice(DeviceName As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager.'
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name As String
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                ' Go through each device detected.'
                Name = CType(info("Caption"), String) ' Get the name of the device.'
                If InStr(Name, DeviceName, CompareMethod.Text) > 0 Then
                    Return True
                End If
            Next
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for'
        Return False
    End Function

If you want to list only USB devices, you may do:

    Function DetectDevice(DeviceName As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager.'
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name As String
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                ' Go through each device detected.'
                Name = CType(info("Caption"), String) ' Get the name of the device.'
                Dim ID As String = CType(info("DeviceID"), String)
                If InStr(info.Path.ToString, "USB\\") Then
                    Console.WriteLine(Name + " " + ID)
                    If InStr(Name, DeviceName, CompareMethod.Text) > 0 Then
                        Return True
                    End If
                End If
            Next
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for'
        Return False
    End Function

I knew this thread from vbforums.com, but it doesn´t work.
I did already imported the system.management with :

Imports System.Management

But it says "Management.ManagementObject"+"System.Management.ManagementObjectSearcher" is not defined.
And with this code I can´t get the status of "Logitech" or another name, what i´m looking for in my usb
periphery.

On my form is a textbox, label and a button. if i write "keyboard" or "logitech" in the textbox and i click on button the label should switch to "is connected" or "is not to connected"...

I´m so sorry, but my programming skills are to low for this, but I want to have this feature in my tool ;)

In Visual Studio go to the Solution Explorer and right click over "References". It will look something like this:

ListDevices0.PNG

A dialog window will be opened. Select "Framework" on the left pane, and click the check box for System.Management.

ListDevices.PNG

Accept and the error should disappear.

ok, got it and how can i search with this code "Logitech" or another name, what i´m looking for in my usb by typing in a textbox?

You should know by now or take a programming course: call the function passing the name of the device as argument.

I´m sorry. Ofcourse I know how to call a function, but I don´t know how to get the result in my case...

    Private Sub Is_USB_Device_Connected_Button_Click_1(sender As Object, e As EventArgs) Handles Is_USB_Device_Connected_Button.Click
        DetectDevice(TextBox1.Text, Label1.Text)
    End Sub

Frankly I'd walk your post back a bit and tell where you are going with this. For example you seem to want it to show you "Logitech something" but that's not always in the data.

What you can see is in USBView at https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/usbview which has full source available for those that want to get into this.

But that's not what I'm asking or why I'm sharing here. I'd like to know what prompted you to go down this rabbit hole.

As you may know, each device has a unique Vendor Identifier (VID) and a Product Identifier (PID). If, for example, I want to know if the mouse is connected, what shall I do? I can list all the devices with their VID and PID. Then unplug the mouse, list again all the devices and compare with the former list and see which device is missing: the missing device will tell me the mouse's VID and PID.
Once I know the VID and PID, it will be possible to detect if the mouse is connected or not.

Imports System.Management

Module Module1

    Sub Main()
        Dim VID_PID_device = "VID_0461&PID_4E22" ' Change to your's 
        Console.WriteLine("1. List All Devices")
        Console.WriteLine("2. List USB Devices")
        Console.WriteLine("3. Find if Device " + VID_PID_device + " is connected.")
        Select Case Console.ReadLine
            Case "1" : ListDevices_VID_PID()
            Case "2" : ListDevices_VID_PID("USB"+Chr(92))
            Case "3" 
                If Find_Device_By_VID_PID(VID_PID_device) Then
                    Console.WriteLine("Connected!")
                End If
        End Select
        Console.Write("Press Enter Key to exit.")
        Console.ReadLine()
    End Sub
    Sub ListDevices_VID_PID(Optional sFilter As String = "")
        Try
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name As String
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                Name = CType(info("Caption"), String)
                Dim ID As String = CType(info("DeviceID"), String)
                If sFilter = "" OrElse InStr(ID, sFilter) Then
                    Console.WriteLine(Name + " " + ID)
                End If
            Next
        Catch ex As Exception

        End Try
    End Sub
    Function Find_Device_By_VID_PID(Device_VID_PID As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager. '
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                ' Go through each device detected.'
                Dim ID As String = CType(info("DeviceID"), String)
                If InStr(info.Path.ToString, Device_VID_PID) Then
                    Return True
                End If
            Next
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for '
        Return False
    End Function

End Module

I changed the code to do it with Textbox, Button and Label.
But it doesn´t find my devices furthermore.
For example : I got 2 Logitech USB-Devices connected. "Logitech G930 Gaming Headset" and "Logitech G19 LCD" (thats the names in the system control center)

here is my code :

Option Strict On
Imports System.Management

Public Class Form1
    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        Dim VID_PID_device = TextBox1.Text ' Change to your's 
        If Find_Device_By_VID_PID(VID_PID_device) Then
            Label1.Text = "Connected!"
        Else
            Label1.Text = "not connected"
        End If
    End Sub

    Sub ListDevices_VID_PID(Optional sFilter As String = "")
        Try
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name As String
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                Name = CType(info("Caption"), String)
                Dim ID As String = CType(info("DeviceID"), String)
                If sFilter = "" OrElse InStr(ID, sFilter) Then
                    Console.WriteLine(Name + " " + ID)
                End If
            Next
        Catch ex As Exception

        End Try
    End Sub
    Function Find_Device_By_VID_PID(Device_VID_PID As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager. '
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                ' Go through each device detected.'
                Dim ID As String = CType(info("DeviceID"), String)
                If InStr(info.Path.ToString, Device_VID_PID) Then
                    Return True
                End If
            Next
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for '
        Return False
    End Function
    End Class

So, why doesn´t find the Device, if I write G930 in the Textbox1?
And another problem is. I learned a few months ago, to use always "Option Strict on", but with this i can´t use it, because ""Option Strict On" does not allow implicit conversions from Integer to Boolean"!?

I'm sooo desperate and confused... ;(

I imagine you'll want to know if the mouse is attached or removed. Here is another version where this task is done (in option 3).

Imports System.Management

Module Module1

    Dim vIDs() As String, iv As Int32 = 0
    Dim VID_PID_device = "VID_0461&PID_4E22" ' Change to your's 
    Dim bDsp As Boolean = True
    Dim bAttached As Boolean = False
    Sub Main()
        Do
            Console.WriteLine("1. List All Devices")
            Console.WriteLine("2. List USB Devices")
            Console.WriteLine("3. Find out the VID and the PID of the mouse.")
            Console.WriteLine("4. Find if Device " + VID_PID_device + " is connected.")
            Console.WriteLine("5. Exit")
            Select Case Console.ReadLine
                Case "1" : ListDevices_VID_PID()
                Case "2" : ListDevices_VID_PID("USB" + Chr(92))
                Case "3"
                    Console.Clear()
                    Console.WriteLine("Press 'Enter' key when the mouse is attached.")
                    Console.ReadLine()
                    bDsp = False
                    iv = 0
                    ListDevices_VID_PID("USB" + Chr(92))
                    Console.WriteLine("Detach the mouse and press 'Enter' key.")
                    Console.ReadLine()
                    ListDevices_VID_PID("USB" + Chr(92))
                    Console.WriteLine("Mouse VID and PID is: " + VID_PID_device)
                    Console.WriteLine("Attach again the mouse and press 'Enter' key.")
                    Console.ReadLine()
                    bAttached = Find_Device_By_VID_PID(VID_PID_device)
                    Console.WriteLine("Now on if you attach/remove it'll be detected. Press any key to exit.")
                    Do
                        Dim nowAttached As Boolean = Find_Device_By_VID_PID(VID_PID_device)
                        If nowAttached <> bAttached Then
                            bAttached = nowAttached
                            If bAttached Then
                                Console.WriteLine("Attached")
                            Else
                                Console.WriteLine("Removed")
                            End If
                        End If
                        System.Threading.Thread.Sleep(500)
                    Loop While Not Console.KeyAvailable
                    bDsp = True
                Case "4"
                    If Find_Device_By_VID_PID(VID_PID_device) Then
                        Console.WriteLine("Connected!")
                    End If
                Case "5" : Exit Do
            End Select
        Loop
    End Sub
    Sub ListDevices_VID_PID(Optional sFilter As String = "")
        Try
            Dim bCompare As Boolean = IIf(iv = 0, False, True)
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name As String
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                Name = CType(info("Caption"), String)
                Dim ID As String = CType(info("DeviceID"), String)
                If sFilter = "" OrElse InStr(ID, sFilter) Then
                    If Not bCompare Then
                        ReDim Preserve vIDs(iv)
                        vIDs(iv) = ID : iv += 1
                    Else
                        Dim pos As Int32 = Array.IndexOf(vIDs, ID)
                        If pos > -1 Then
                            vIDs(pos) = ""
                        End If
                    End If
                    If bDsp Then Console.WriteLine(Name + " " + ID)
                End If
            Next
            For i As Int32 = 0 To vIDs.Length - 1
                If vIDs(i).Length Then
                    VID_PID_device = Split(vIDs(i), "\")(1)
                    Exit For
                End If
            Next
        Catch ex As Exception

        End Try
    End Sub

    Function Find_Device_By_VID_PID(Device_VID_PID As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager. '
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                ' Go through each device detected.'
                Dim ID As String = CType(info("DeviceID"), String)
                If InStr(info.Path.ToString, Device_VID_PID) Then
                    Return True
                End If
            Next
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for '
        Return False
    End Function

End Module

Please have a look at my post 1 minute earlier then your post ;)

Or is it only possible to search VID_PID? I thougt it is possible to search only for a name...
Because, I think VID_PID is like a searialnumber and it will be allways different at my pc to another pc!?!

Vendor ID (VID) and Product (ID) is not the same as serial number. Two equal devices from the same vendor will have the same VID & PID because are the same product from the same vendor, but different serial numbers.
I have made same changes to the code so you can find also a device by name:

Imports System.Management

Module Module1

    Dim vIDs() As String, iv As Int32 = 0
    Dim deviceID = "VID_0461&PID_4E22" ' Change to your's 
    Dim bDsp As Boolean = True
    Dim bAttached As Boolean = False
    Sub Main()
        Do
            Console.WriteLine("1. List All Devices")
            Console.WriteLine("2. List USB Devices")
            Console.WriteLine("3. Find out the device ID")
            Console.WriteLine("4. Find if Device " + deviceID + " is connected.")
            Console.WriteLine("5. Find device(s) by name.")
            Console.WriteLine("6. Exit")
            Select Case Console.ReadLine
                Case "1" : Detect_missing_VID_PID()
                Case "2" : Detect_missing_VID_PID("USB" + Chr(92))
                Case "3"
                    Console.Clear()
                    Console.WriteLine("Press 'Enter' key when the device is attached.")
                    Console.ReadLine()
                    bDsp = False
                    iv = 0
                    Detect_missing_VID_PID("USB" + Chr(92))
                    Console.WriteLine("Detach the device and press 'Enter' key.")
                    Console.ReadLine()
                    Detect_missing_VID_PID("USB" + Chr(92))
                    Console.WriteLine("Device ID is: " + deviceID)
                    Console.WriteLine("Attach again the device and press 'Enter' key.")
                    Console.ReadLine()
                    bAttached = Find_Device_By_ID(deviceID)
                    Console.WriteLine("Now on if you attach/remove it'll be detected. Press any key to exit.")
                    Do
                        Dim nowAttached As Boolean = Find_Device_By_ID(deviceID)
                        If nowAttached <> bAttached Then
                            bAttached = nowAttached
                            If bAttached Then
                                Console.WriteLine("Attached")
                            Else
                                Console.WriteLine("Removed")
                            End If
                        End If
                        System.Threading.Thread.Sleep(500)
                    Loop While Not Console.KeyAvailable
                    bDsp = True
                Case "4"
                    If Find_Device_By_ID(deviceID) Then
                        Console.WriteLine("Connected!")
                    End If
                Case "5"
                    Console.Write("Device's name is?: ")
                    Dim name As String = Console.ReadLine
                    Find_Device_By_Name(name)
                Case "6" : Exit Do
            End Select
        Loop
    End Sub
    Sub Detect_missing_VID_PID(Optional sFilter As String = "")
        ' Called 2 times: '
        ' 1. When device is connected '
        ' 2. When device is removed '
        Try
            Dim bCompare As Boolean = IIf(iv = 0, False, True)
            Dim info As Management.ManagementObject
            Dim search As System.Management.ManagementObjectSearcher
            Dim Name As String
            search = New System.Management.ManagementObjectSearcher("SELECT * From Win32_PnPEntity")
            For Each info In search.Get()
                Name = CType(info("Caption"), String)
                Dim ID As String = CType(info("DeviceID"), String)
                If sFilter = "" OrElse InStr(ID, sFilter) Then
                    If Not bCompare Then
                        ReDim Preserve vIDs(iv)
                        vIDs(iv) = ID : iv += 1
                    Else
                        Dim pos As Int32 = Array.IndexOf(vIDs, ID)
                        If pos > -1 Then
                            vIDs(pos) = ""
                        End If
                    End If
                    If bDsp Then Console.WriteLine(Name + " " + ID)
                End If
            Next
            For i As Int32 = 0 To vIDs.Length - 1
                If vIDs(i).Length Then
                    deviceID = vIDs(i)
                    Exit For
                End If
            Next
        Catch ex As Exception

        End Try
    End Sub

    Function Find_Device_By_ID(Device_ID As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager. '
            Dim info As Management.ManagementObject
            Dim search As New System.Management.ManagementObjectSearcher(
                "SELECT * FROM Win32_PnPEntity WHERE DeviceID='" +
                Replace(Device_ID, Chr(92), "\\") + "'")
            For Each info In search.Get()
                Return True ' Device has been Found '
            Next
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for '
        Return False
    End Function
    Function Find_Device_By_Name(name As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager. '
            Dim info As Management.ManagementObject
            Dim search As New System.Management.ManagementObjectSearcher(
                "SELECT * FROM Win32_PnPEntity WHERE Name='" + name + "'")
            For Each info In search.Get()
                Dim ID As String = CType(info("DeviceID"), String)
                Console.WriteLine("Device ID is: " + ID.ToString)
                Return True ' Device has been Found '
            Next
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for '
        Return False
    End Function

End Module

BTW you may cast from one type to another by means of DirectCast() or CType().

ok, I only need the function "find_device_by_name".
I tried your console-version, after Question Devices name is "g930" nothing happens and it starts again with selection.
After this i tried it by changing it to my code with textbox and msgboxes to see where it is. So it doesn´t start with "For Each info..." and there is no exception too.

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        'Console.Write("Device's name is?: ")
        Dim name As String = TextBox1.Text
        Find_Device_By_Name(name)
    End Sub

    Function Find_Device_By_Name(name As String) As Boolean
        Try
            MsgBox("1")
            ' See if the desired device shows up in the device manager. '
            Dim info As Management.ManagementObject
            Dim search As New System.Management.ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Name='" + name + "'")
            MsgBox("2")
            For Each info In search.Get()
                Dim ID As String = CType(info("DeviceID"), String)
                Label1.Text = "Device ID is: " + ID.ToString
                MsgBox("3")
                Return True ' Device has been Found '
                MsgBox("4")
            Next
        Catch ex As Exception
            MsgBox("5")
        End Try
        'We did not find the device we were looking for '
        Return False
    End Function

¿Are you entering the complete name? The select command is NOT case sensitive, but if you want to use the percent wildcard '%', the function would be then:

    Function Find_Device_By_Name(name As String) As Boolean
        Try
            ' See if the desired device shows up in the device manager. '
            Dim info As Management.ManagementObject
            Dim search As New System.Management.ManagementObjectSearcher(
                "SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%" + name + "%'")
            For Each info In search.Get()
                Dim devname As String = CType(info("Name"), String)
                Dim ID As String = CType(info("DeviceID"), String)
                Console.WriteLine("Device ID is: " + ID.ToString)
                Console.WriteLine("       name=" + devname)
            Next
            Return True ' Device(s) Found '
        Catch ex As Exception

        End Try
        'We did not find the device we were looking for '
        Return False
    End Function

I wouldn't count on "G930" showing up. Maybe by vid and pid but by name, would not count on that. Also, why are you doing this? Your mention of a serial number has me worried you are looking for non-existant data.

Again, "Frankly I'd walk your post back a bit and tell where you are going with this. For example you seem to want it to show you "Logitech something" but that's not always in the data.

What you can see is in USBView at https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/usbview which has full source available for those that want to get into this.

But that's not what I'm asking or why I'm sharing here. I'd like to know what prompted you to go down this rabbit hole."

There should be no problem by name. Could you upload an image of the Console listing the name (option 2.) ? Use the snipping tool for that purpose.

commented: I agree but I've seen folk go down this rabbit hole and the name wasn't in the data. +15

It works now, with your last code. Thank you.
Here is the image from the console.

Unbenannt.png

I am very happy that you could resolve the issue. Thanks.

I continue this thread because actually I've re-written some C# code, that communicates with a usb device, in Visual Basic.
The thing is that when trying to find the COM port to which the device is connected at, the code was throwing an InvalidCastException. After searching a while the internet the solution is not to call the function directly, but through a thread:

    Function FindDeviceAndOpen() As Boolean
        Try
            If Not IsOpen Then
                If sCom = "" Then
                    Dim o As New sComObj
                    Dim t As New System.Threading.Thread(AddressOf SearchComPort)
                    t.Start(o)
                    t.Join()
                    sCom = o.sCom
                End If
            End If
            If sCom IsNot Nothing AndAlso sCom.Length Then
                Open()
            End If
        Catch ex As Exception

        End Try
    End Function
    Class sComObj
        Public sCom As String
    End Class
    Sub SearchComPort(obj As sComObj)
        Try
            Dim info As Management.ManagementObject
            Dim searcher As System.Management.ManagementObjectSearcher _
                    = New System.Management.ManagementObjectSearcher(
                "SELECT * FROM Win32_PnPEntity WHERE DeviceID Like '%vid_" + VID + "&pid_" + PID + "%'")
            For Each info In searcher.Get()
                sCom = CType(info("name"), String)
                Dim pos As Int32 = InStrRev(sCom, "(")
                sCom = Mid(sCom, pos + 1)
                obj.sCom = Mid(sCom, 1, Len(sCom) - 1)
                info.Dispose()
                searcher.Dispose()
                Exit For
            Next
        Catch ex As Exception

        End Try
    End Sub

Still the code was throwing exceptions until the function shifted to a shared function and the code was as below. Now it works smoothly.

    Shared Function SearchComPort(obj As sComObj) As Boolean
        Try
            obj.sCom = ""
            Dim sCom As String
            Dim info As Management.ManagementObject
            Dim searcher As New System.Management.ManagementObjectSearcher(
                "SELECT * FROM Win32_PnPEntity where deviceID like '%usb%'")
            For Each info In searcher.Get()
                Dim deviceID As String = info("deviceID").ToString
                If InStr(LCase(deviceID), LCase("vid_" + obj.VID + "&pid_" + obj.PID)) Then
                    sCom = CType(info("name"), String)
                    Dim pos As Int32 = InStrRev(sCom, "(")
                    sCom = Mid(sCom, pos + 1)
                    sCom = Mid(sCom, 1, Len(sCom) - 1)
                    obj.sCom = sCom
                    Return True
                End If
            Next
        Catch ex As Exception

        End Try
        Return False
    End Function

Had to do something like this real quick and I come up with this

 Function GetBluetoothConnectedDevices() As List(Of String)
    Dim R As New List(Of String)
    Try
        Dim searcher As New ManagementObjectSearcher(New ManagementScope("\\.\root\CIMV2", Nothing), New WqlObjectQuery("Select Name from Win32_PnPEntity where pnpclass = 'bluetooth' and service is null and description = 'bluetooth device'"), Nothing)
        For Each share As ManagementObject In searcher.[Get]()
            Try
                If Not IsNothing(share("Name")) AndAlso share("Name").ToString.Trim = "" Then R.Add(share("Name").ToString.Trim)
            Catch
                Continue For
            End Try
        Next
    Catch
    End Try
    Return R
End Function
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.