⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 frmmain.vb

📁 microsoft winusb interface for vb
💻 VB
📖 第 1 页 / 共 4 页
字号:

            'Define a delegate using the IAsyncResult object.

            Dim deleg As ReadFromDeviceDelegate = _
                DirectCast(ar.AsyncState, ReadFromDeviceDelegate)

            'Get the IAsyncResult object and the values of other paramaters that the
            'BeginInvoke method passed ByRef.

            deleg.EndInvoke(receivedDataBuffer, bytesRead, success, ar)

            'Display the received data in the form's list box.

            If (ar.IsCompleted And success) Then

                MyMarshalToForm("AddItemToListBox", "Data received via interrupt transfer:")

                MyMarshalToForm("AddItemToListBox", " Received Data:")

                For count = 0 To receivedDataBuffer.GetUpperBound(0)

                    ' Convert the byte value to a 2-character hex string.

                    byteValue = String.Format("{0:X2} ", receivedDataBuffer(count))

                    MyMarshalToForm("AddItemToListBox", " " & byteValue)

                Next count

            Else
                MyMarshalToForm("AddItemToListBox", "The attempt to read interrupt data has failed.")
                myDeviceDetected = False

            End If

            MyMarshalToForm("ScrollToBottomOfListBox", "")

            'Enable requesting another transfer.

            MyMarshalToForm("EnableCmdSendandReceiveViaInterruptTransfers", "")

        Catch ex As Exception
            Throw
        End Try

    End Sub

    ''' <summary>
    ''' Initializes elements on the form.
    ''' </summary>

    Private Sub InitializeDisplay()

        Dim byteValue As String
        Dim count As Short

        Try

            'Create dropdown list boxes.

            For count = 0 To 255

                byteValue = String.Format("{0:X2} ", count)

                frmMy.cboInterruptOutByte0.Items.Insert(count, byteValue)
                frmMy.cboInterruptOutByte1.Items.Insert(count, byteValue)
                frmMy.cboControlOutByte0.Items.Insert(count, byteValue)
                frmMy.cboControlOutByte1.Items.Insert(count, byteValue)

            Next count

            'Select a default value for each box

            frmMy.cboInterruptOutByte0.SelectedIndex = 0
            frmMy.cboInterruptOutByte1.SelectedIndex = 128
            frmMy.cboControlOutByte0.SelectedIndex = 65
            frmMy.cboControlOutByte1.SelectedIndex = 53

            If Not (myWinUsbDevice.IsWindowsXpOrLater()) Then

                lstResults.Items.Add("The operating system is not Windows XP or later.")
                lstResults.Items.Add("The WinUsb driver requires Windows XP or later.")

            End If

        Catch ex As Exception
            Throw
        End Try

    End Sub

    ''' <summary>
    ''' Initiates a Control Read transfer. (Data stage is device to host.)
    ''' </summary>
    ''' 
    Sub InitiateControlInTransfer()
        Dim bResult As Boolean
        Dim formText As String
        Dim dataStage(1) As Byte

        Try
            'If the device hasn't been detected, was removed, or timed out on a previous attempt
            'to access it, look for the device.

            myDeviceDetected = DetectDevice()

            If myDeviceDetected Then

                bResult = myWinUsbDevice.Do_Control_Read_Transfer(dataStage)

                If bResult Then

                    formText = "Bytes received via Control Read transfer:"
                    AccessForm("AddItemToListBox", formText)

                    For i As Integer = 0 To dataStage.Length - 1
                        formText = String.Format("{0:X2} ", dataStage(i))
                        AccessForm("AddItemToListBox", formText)
                    Next i

                Else
                    formText = "Control Read transfer failed."
                    AccessForm("AddItemToListBox", formText)
                    myDeviceDetected = False
                End If
            End If

            ScrollToBottomOfListBox()

        Catch ex As Exception
            Throw
        End Try

    End Sub

    ''' <summary>
    ''' Initiates a Control Write transfer. (Data stage is host to device.)
    ''' </summary>
    ''' 
    Private Sub InitiateControlOutTransfer()
        Dim bResult As Boolean
        Dim comboBoxText As String
        Dim dataStage(1) As Byte
        Dim formText As String

        Try
            'If the device hasn't been detected, was removed, or timed out on a previous attempt
            'to access it, look for the device.

            myDeviceDetected = DetectDevice()

            If myDeviceDetected Then

                ' Get the value to send as a hex string.

                comboBoxText = _
                    System.Convert.ToString(cboControlOutByte0.SelectedItem).TrimEnd(Nothing)

                ' Convert the string to a byte.

                dataStage(0) = _
                        Convert.ToByte(String.Format("{0:X2}", comboBoxText), 16)

                ' Get the value to send as a hex string.

                comboBoxText = _
                    System.Convert.ToString(cboControlOutByte1.SelectedItem).TrimEnd(Nothing)

                ' Convert the string to a byte.

                dataStage(1) = _
                        Convert.ToByte(String.Format("{0:X2}", comboBoxText), 16)

                bResult = myWinUsbDevice.Do_Control_Write_Transfer(dataStage)

                If bResult Then
                    formText = "Control Write transfer completed successfully."
                Else
                    formText = "Control Write transfer failed."
                    myDeviceDetected = False
                End If

                AccessForm("AddItemToListBox", formText)
            End If

            ScrollToBottomOfListBox()

        Catch ex As Exception
            Throw
        End Try

    End Sub

    ''' <summary>
    ''' Enables accessing a form from another thread 
    ''' </summary>
    ''' 
    ''' <param name="action"> A string that names the action to perform on the form. </param>
    ''' <param name="textToDisplay"> Text that the form displays or uses for 
    ''' another purpose. Actions that don't use text ignore this parameter. </param>

    Private Sub MyMarshalToForm _
        (ByVal action As String, _
        ByVal textToDisplay As String)

        Dim args() As Object = {action, textToDisplay}
        Dim MarshalToFormDelegate As MarshalToForm

        Try
            ' The AccessForm routine contains the code that accesses the form.

            MarshalToFormDelegate = New MarshalToForm(AddressOf AccessForm)

            ' Execute AccessForm, passing the parameters in args.

            MyBase.Invoke(MarshalToFormDelegate, args)

        Catch ex As Exception
            Throw
        End Try

    End Sub

    ''' <summary>
    ''' Called when a WM_DEVICECHANGE message has arrived,
    ''' indicating that a device has been attached or removed.
    ''' </summary>
    ''' 
    ''' <param name="m"> A message with information about the device. </param>

    Friend Sub OnDeviceChange(ByVal m As Message)

        Try
            If (m.WParam.ToInt32 = DBT_DEVICEARRIVAL) Then

                ' If WParam contains DBT_DEVICEARRIVAL, a device has been attached.
                ' Find out if it's the device we're communicating with.

                If myDeviceManagement.DeviceNameMatch(m, myDevicePathName) Then
                    lstResults.Items.Add("My device attached.")
                End If

            ElseIf (m.WParam.ToInt32 = DBT_DEVICEREMOVECOMPLETE) Then

                ' If WParam contains DBT_DEVICEREMOVAL, a device has been removed.
                ' Find out if it's the device we're communicating with.

                If myDeviceManagement.DeviceNameMatch(m, myDevicePathName) Then

                    lstResults.Items.Add("My device removed.")

                    ' Set MyDeviceDetected False so on the next data-transfer attempt,
                    ' FindMyDevice() will be called to look for the device 
                    ' and get a new handle.

                    frmMy.myDeviceDetected = False

                End If
            End If

            ScrollToBottomOfListBox()

        Catch ex As Exception
            Throw
        End Try
    End Sub

    ''' <summary>
    ''' Initiates a read operation from a bulk IN endpoint.
    ''' To enable reading without blocking the main thread, uses an asynchronous delegate.
    ''' </summary>
    ''' 
    ''' <remarks>
    ''' To enable reading more than 64 bytes (with device firmware support), increase bytesToRead.
    ''' </remarks> 

    Private Sub ReadDataViaBulkTransfer()

        Dim ar As IAsyncResult
        Dim buffer(63) As Byte
        Dim bytesRead As UInt32
        Dim bytesToRead As UInt32 = 64
        Dim success As Boolean

        ' Define a delegate for the ReadViaBulkTransfer method of WinUsbDevice.

        Dim MyReadFromDeviceDelegate As _
            New ReadFromDeviceDelegate(AddressOf myWinUsbDevice.ReadViaBulkTransfer)

        Try

            ' The BeginInvoke method calls MyWinUsbDevice.ReadViaBulkTransfer to attempt 
            ' to read data. The method has the same parameters as ReadViaBulkTransfer,
            ' plus two additional parameters:
            ' GetReceivedBulkData is the callback routine that executes when 
            ' ReadViaBulkTransfer returns.
            ' MyReadFromDeviceDelegate is the asynchronous delegate object.

            ar = MyReadFromDeviceDelegate.BeginInvoke _
                (CByte(myWinUsbDevice.myDevInfo.bulkInPipe), _
                bytesToRead, _
                buffer, _
                bytesRead, _
                success, _
                New AsyncCallback(AddressOf GetReceivedBulkData), _
                MyReadFromDeviceDelegate)

        Catch ex As Exception
            Throw
        End Try
    End Sub

    ''' <summary>
    ''' Initiates a read operation from an interrupt IN endpoint.
    ''' To enable reading without blocking the main thread, uses an asynchronous delegate.
    ''' </summary>
    ''' 
    ''' <remarks>
    ''' To enable reading more than 2 bytes (with device firmware support), increase bytesToRead.
    ''' </remarks>

    Private Sub ReadDataViaInterruptTransfer()

        Dim ar As IAsyncResult
        Dim buffer(1) As Byte
        Dim bytesRead As UInt32
        Dim bytesToRead As UInt32 = 2
        Dim success As Boolean

        Try
            ' Define a delegate for the ReadViaInterruptTransfer method of WinUsbDevice.

            Dim MyReadFromDeviceDelegate As _
                New ReadFromDeviceDelegate(AddressOf myWinUsbDevice.ReadViaInterruptTransfer)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -