使用USB vb.net与规模通信

时间:2014-12-17 14:42:26

标签: vb.net

我有一个项目正在编写VB.net代码,该代码将使用USB与运输规模进行通信。不幸的是我之前从未写过任何与USB通信的内容,所以我不知道如何解决这个问题。我搜索过网络,发现有很多方法可以用C#来做。但是我在VB.net找到的一切都无法发挥作用。我遇到了这个看起来很有希望的代码,不幸的是我收到了错误“System.Managermant.ManagementObject未定义”。我导入了System.management,但仍然有错误。我需要一个如何与USB设备通信的示例

Imports System.Management

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim strDeviceName As String
        Dim strQuotes As String
        Dim arrDeviceNames As Array
        Dim USBDevice As System.Management.ManagementObject
        Dim objReturnCollection As System.Management.ManagementObjectCollection

        'Dim ObjScope As New System.Management.ManagementScope("\\FullNameOfYourComputer\root\cimv2")    'This is optional. Can be used for remote connections.

        Dim SearcherUSBDevicesCollection As New System.Management.ManagementObjectSearcher("Select * from Win32_USBControllerDevice")
        Dim ReturnUSBDevicesCollection As System.Management.ManagementObjectCollection
        ReturnUSBDevicesCollection = SearcherUSBDevicesCollection.Get

        'Or
        'Dim USBDevicesClass As New System.Management.ManagementClass("Win32_USBControllerDevice")
        'Dim ReturnUSBDevicesCollection As System.Management.ManagementObjectCollection = USBDevicesClass.GetInstances()


        For Each USBDevice In ReturnUSBDevicesCollection
            strDeviceName = USBDevice.Properties("Dependent").Value.ToString()
            strQuotes = Chr(34)
            strDeviceName = Replace(strDeviceName, strQuotes, "")
            arrDeviceNames = Split(strDeviceName, "=")
            strDeviceName = arrDeviceNames(1)

            Dim objSearcher As New System.Management.ManagementObjectSearcher("Select * From Win32_PnPEntity Where DeviceID = '" & strDeviceName & "'")
            objReturnCollection = objSearcher.Get()

            Dim objReturn As System.Management.ManagementObject

            For Each objReturn In objReturnCollection
                Me.ListBox4.Items.Add("Description: " & objReturn("Name").ToString())
                Me.ListBox4.Items.Add("DeviceID: " & objReturn("DeviceID").ToString())

            Next
        Next

    End Sub
End Class

1 个答案:

答案 0 :(得分:2)

转到项目设置并添加对System.Management的引用。