📄 frmmain.vb
字号:
Me.Controls.Add(Me.fraControlOutTransfer)
Me.Controls.Add(Me.cmdFindDevice)
Me.Controls.Add(Me.fraControlInTransfer)
Me.Controls.Add(Me.fraBulkTransfer)
Me.Controls.Add(Me.fraInterruptTransfer)
Me.Controls.Add(Me.lstResults)
Me.Font = New System.Drawing.Font("Arial", 8.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Location = New System.Drawing.Point(21, 28)
Me.Name = "frmMain"
Me.StartPosition = System.Windows.Forms.FormStartPosition.Manual
Me.Text = "WinUSB Demo"
Me.fraControlInTransfer.ResumeLayout(False)
Me.fraBulkTransfer.ResumeLayout(False)
Me.fraBulkTransfer.PerformLayout()
Me.fraInterruptTransfer.ResumeLayout(False)
Me.fraControlOutTransfer.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
#End Region
' This GUID must match the GUID in the device's INF file.
' To create a GUID in Visual Studio, click Tools > Create GUID.
Public Const WINUSB_DEMO_GUID_STRING As String = "{42CA71EC-CE1C-44c2-82DE-87D8D8FF6C1E}"
Dim deviceNotificationHandle As IntPtr
Dim myDeviceDetected As Boolean = False
Dim myDeviceManagement As New DeviceManagement()
Dim myDevicePathName As String
Dim myWinUsbDevice As New WinUsbDevice()
Friend frmMy As frmMain
''' <summary>
''' Define a class of delegates with the same parameters as
''' WinUsbDevice.ReadViaBulkTransfer and WinUsbDevice.ReadViaInterruptTransfer.
''' Used for asynchronous reads from the device.
''' </summary>
Private Delegate Sub ReadFromDeviceDelegate _
(ByVal pipeID As Byte, _
ByVal bufferLength As UInt32, _
ByRef buffer() As Byte, _
ByRef lengthTransferred As UInt32, _
ByRef success As Boolean)
''' <summary>
''' Define a delegate with the same parameters as AccessForm.
''' Used in accessing the application's form from a different thread.
''' </summary>
Private Delegate Sub MarshalToForm _
(ByVal action As String, _
ByVal textToAdd As String)
''' <summary>
''' In asynchronous calls to WinUsb_ReadPipe, the callback function
''' uses this routine to access the application's form, which runs in
''' a different thread.
''' The routine performs various application-specific functions that
''' involve accessing the application's form.
''' </summary>
'''
''' <param name="action"> A string that names the action to perform on the form. </param>
''' <param name="formText"> Text to display on the form or an empty string. </param>
'''
Private Sub AccessForm(ByVal action As String, ByVal formText As String)
Try
' Select an action to perform on the form:
Select Case action
Case "AddItemToListBox"
lstResults.Items.Add(formText)
Case "AddItemToTextBox"
txtBulkDataToSend.SelectedText = formText & vbCrLf
Case "EnableCmdSendandReceiveViaBulkTransfers"
cmdSendandRecieveViaBulkTransfers.Enabled = True
Case "EnableCmdSendandReceiveViaInterruptTransfers"
cmdSendAndReceiveViaInterruptTransfers.Enabled = True
Case "ScrollToBottomOfListBox"
lstResults.SelectedIndex = lstResults.Items.Count - 1
Case Else
End Select
Catch ex As Exception
Throw
End Try
End Sub
''' <summary>
''' If the device hasn't been detected, look for it.
''' </summary>
'''
''' <returns>
''' True if the device is detected, False if not detected.
''' </returns>
'''
Private Function DetectDevice() As Boolean
Try
If (myDeviceDetected = False) Then
myDeviceDetected = FindMyDevice()
End If
Return myDeviceDetected
Catch ex As Exception
Throw
End Try
End Function
''' <summary>
''' Display the device's speed in the list box.
''' </summary>
'''
''' <remarks>
''' Precondition: device speed was obtained by calling WinUsb_QueryDeviceInformation
''' and stored in myDevInfo.
''' </remarks >
Private Sub DisplayDeviceSpeed()
Dim speed As String = ""
myWinUsbDevice.QueryDeviceSpeed()
Try
Select Case myWinUsbDevice.myDevInfo.devicespeed
Case 0
speed = "low"
Case 1
speed = "full"
Case 2
speed = "high"
End Select
lstResults.Items.Add("Device speed = " & speed)
Catch ex As Exception
Throw
End Try
End Sub
''' <summary>
''' Locate a device with a particular
''' device interface GUID. Open a handle to the device.
''' </summary>
'''
''' <returns>
''' True if the device is detected, False if not detected.
''' </returns>
Private Function FindMyDevice() As Boolean
Dim deviceFound As Boolean
Dim devicePathName As String = ""
Dim lastDevice As Boolean = False
Dim result As Boolean
Dim success As Boolean
Try
If Not myDeviceDetected Then
' Convert the device interface GUID string to a GUID object:
Dim winUsbDemoGuid As New System.Guid(WINUSB_DEMO_GUID_STRING)
'Fill an array with the device path names of all attached devices with matching GUIDs.
deviceFound = myDeviceManagement.FindDeviceFromGuid _
(winUsbDemoGuid, _
devicePathName)
If deviceFound = True Then
myWinUsbDevice.GetDeviceHandle(devicePathName)
If (myWinUsbDevice.deviceHandle <> INVALID_HANDLE_VALUE) Then
lstResults.Items.Add("Device detected:")
ScrollToBottomOfListBox()
myDeviceDetected = True
'Save DevicePathName so OnDeviceChange() knows which name is my device.
myDevicePathName = devicePathName
Else
'There was a problem in retrieving the information.
myDeviceDetected = False
result = CloseHandle(myWinUsbDevice.deviceHandle)
End If
End If
If myDeviceDetected Then
'The device was detected.
'Register to receive notifications if the device is removed or attached.
success = myDeviceManagement.RegisterForDeviceNotifications _
(myDevicePathName, _
frmMy.Handle, _
winUsbDemoGuid, _
deviceNotificationHandle)
If success Then
myWinUsbDevice.InitializeDevice(myWinUsbDevice.deviceHandle)
DisplayDeviceSpeed()
End If
Else
lstResults.Items.Add("Device not found.")
cmdSendandRecieveViaBulkTransfers.Enabled = True
cmdSendAndReceiveViaInterruptTransfers.Enabled = True
End If
Else
lstResults.Items.Add("Device detected.")
End If
ScrollToBottomOfListBox()
Return myDeviceDetected
Catch ex As Exception
Throw
End Try
End Function
''' <summary>
''' Retrieves received data from a bulk endpoint.
''' This routine is called automatically when myWinUsbDevice.ReadViaBulkTransfer
''' returns. The routine calls several marshaling routines to access the main form.
''' </summary>
'''
''' <param name="ar"> An object containing status information about the
''' asynchronous operation.</param>
'''
Private Sub GetReceivedBulkData(ByVal ar As IAsyncResult)
Dim bytesRead As UInt32
Dim myEncoder As New System.Text.ASCIIEncoding
Dim receivedDataBuffer As Byte()
Dim receivedtext As String
Dim success As Boolean
Try
receivedDataBuffer = Nothing
'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 bulk transfer:")
' Convert the received bytes to a string for display.
receivedtext = myEncoder.GetString(receivedDataBuffer)
MyMarshalToForm("AddItemToListBox", receivedtext)
Else
MyMarshalToForm("AddItemToListBox", "The attempt to read bulk data has failed.")
myDeviceDetected = False
End If
MyMarshalToForm("ScrollToBottomOfListBox", "")
'Enable requesting another transfer.
MyMarshalToForm("EnableCmdSendandReceiveViaBulkTransfers", "")
Catch ex As Exception
Throw
End Try
End Sub
''' <summary>
''' Retrieves received data from an interrupt endpoint.
''' This routine is called automatically when myWinUsbDevice.ReadViaInterruptTransfer
''' returns. The routine calls several marshaling routines to access the main form.
''' </summary>
'''
''' <param name="ar"> An object containing status information about the
''' asynchronous operation.</param>
Private Sub GetReceivedInterruptData(ByVal ar As IAsyncResult)
Dim byteValue As String
Dim bytesRead As UInt32
Dim count As Integer
Dim receivedDataBuffer As Byte()
Dim success As Boolean
Try
receivedDataBuffer = Nothing
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -