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

📄 frmmain.vb

📁 visual basic 2005 express 写的上位机
💻 VB
📖 第 1 页 / 共 4 页
字号:
    'To view additional debugging messages, in the Visual Studio development environment,
    'select the Debug build (Build > Configuration Manager > Active Solution Configuration)
    'and view the Output window (View > Other Windows > Output)

    'The application uses a Delegate and the BeginInvoke and EndInvoke methods to read
    'Input reports asynchronously, so the application's main thread doesn't have to
    'wait for the device to return an Input report when the HID driver's buffer is empty. 

    'If you want to only receive data or only send data, comment out the unwanted code 
    '(In ExchangeInputAndOutputReports or ExchangeFeatureReports, comment out
    'the "Success = " line and the "If Success" block that follows it).

    'This project includes the following modules:
    'frmMain.vb - routines specific to the form.
    'Hid.vb - routines specific to HID communications.
    'DeviceManagement.vb - routines for obtaining a handle to a device from its GUID
    'and receiving device notifications. This routines are not specific to HIDs.
    'Debugging.vb - contains a routine for displaying API error messages.

    'HidDeclarations.vb - Declarations for API functions used by Hid.vb.
    'FileIODeclarations.vb - Declarations for file-related API functions.
    'DeviceManagementDeclarations.vb - Declarations for API functions used by DeviceManagement.vb.
    'DebuggingDeclarations.vb - Declarations for API functions used by Debugging.vb.

    'Companion device firmware for several device CPUs is available from www.Lvr.com/hidpage.htm.
    'You can use any generic HID (not a system mouse or keyboard) that sends and receives reports.

    'New in version 2.3:
    'In the asychronous ReadFiles, the GetInputReportData callback routine uses marshaling to 
    'perform actions on the form, which runs in a different thread. 
    'The marshaling is required by the .NET Framework 2.0. 
    'I also fixed a few other things that the compiler complained about.

    'New in version 2.2:
    'The application obtains separate handles for device information/Feature reports,
    'Input reports, and Output reports. This enables getting information about
    'mice and keyboards.
    'The application detects if the device is a mouse or keyboard
    'and warns that Windows 2000/XP will not allow exchanging Input or Output reports.
    'The list box's contents are trimmed when they get too large. 

    'For more information about HIDs and USB, and additional example device firmware to use
    'with this application, visit Lakeview Research at http://www.Lvr.com .

    'Send comments, bug reports, etc. to jan@Lvr.com .

    'This application has been tested under Windows 98SE, Windows 2000, and Windows XP.

    Dim DeviceNotificationHandle As IntPtr
    Dim ExclusiveAccess As Boolean
    Dim HIDHandle As Integer
    Dim HIDUsage As String
    Dim MyDeviceDetected As Boolean
    Dim MyDevicePathName As String
    Dim MyHID As New Hid()
    Dim ReadHandle As Integer
    Dim WriteHandle As Integer

    'Dim InputReportBuffer As Byte()

    'Used only in viewing results of API calls in debug.write statements:

    Dim MyDebugging As New Debugging()

    Dim MyDeviceManagement As New DeviceManagement()

    Friend frmMy As frmMain

    'Define a class of delegates that point to the Hid.DeviceReport.Read function.
    'This delegate has the same parameters as Hid.DeviceReport.Read.
    'Used for asynchronous reads from the device.

    Private Delegate Sub ReadInputReportDelegate _
        (ByVal readHandle As Integer, _
        ByVal hidHandle As Integer, _
        ByVal writeHandle As Integer, _
        ByRef myDeviceDetected As Boolean, _
        ByRef readBuffer() As Byte, _
        ByRef success As Boolean)

    'This delegate has the same parameters as AccessForm.
    'Used in accessing the application's form from a different thread.

    Private Delegate Sub MarshalToForm _
        (ByVal action As String, _
        ByVal textToAdd As String)


    Friend Sub OnDeviceChange(ByVal m As Message)

        'Purpose    : Called when a WM_DEVICECHANGE message has arrived,
        '           : indicating that a device has been attached or removed.

        'Accepts    : m - a message with information about the device

        Debug.WriteLine("WM_DEVICECHANGE")

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

                'If WParam contains DBT_DEVICEARRIVAL, a device has been attached.

                Debug.WriteLine("A device has been attached.")

                'Find out if it's the device we're communicating with.


            ElseIf (m.WParam.ToInt32 = DBT_DEVICEREMOVECOMPLETE) Then

                'If WParam contains DBT_DEVICEREMOVAL, a device has been removed.

                Debug.WriteLine("A device has been removed.")

                'Find out if it's the device we're communicating with.

                If MyDeviceManagement.DeviceNameMatch(m, MyDevicePathName) Then

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

                    frmMy.MyDeviceDetected = False
                End If
            End If

            Call ScrollToBottomOfListBox()

        Catch ex As Exception
            Call HandleException(Me.Name, ex)
        End Try
    End Sub


    Private Function FindTheHid() As Boolean

        'Purpose    : Uses a series of API calls to locate a HID-class device
        '           ; by its Vendor ID and Product ID.

        'Returns    : True if the device is detected, False if not detected.

        Dim DeviceFound As Boolean
        Dim DevicePathName(127) As String
        Dim GUIDString As String
        Dim HidGuid As System.Guid
        Dim LastDevice As Boolean
        Dim MemberIndex As Integer
        Dim MyProductID As Short
        Dim MyVendorID As Short
        Dim Result As Boolean
        Dim Security As SECURITY_ATTRIBUTES
        Dim Success As Boolean

        Try

            HidGuid = Guid.Empty
            LastDevice = False
            MyDeviceDetected = False

            'Values for the SECURITY_ATTRIBUTES structure:

            Security.lpSecurityDescriptor = 0
            Security.bInheritHandle = CInt(True)
            Security.nLength = Len(Security)

            'Get the device's Vendor ID and Product ID from the form's text boxes.

            GetVendorAndProductIDsFromTextBoxes(MyVendorID, MyProductID)

            '***
            'API function: 'HidD_GetHidGuid

            'Purpose: Retrieves the interface class GUID for the HID class.

            'Accepts: 'A System.Guid object for storing the GUID.
            '***

            HidD_GetHidGuid(HidGuid)
            Debug.WriteLine(MyDebugging.ResultOfAPICall("GetHidGuid"))

            'Display the GUID.

            GUIDString = HidGuid.ToString
            Debug.WriteLine("  GUID for system HIDs: " & GUIDString)

            'Fill an array with the device path names of all attached HIDs.

            DeviceFound = MyDeviceManagement.FindDeviceFromGuid _
                (HidGuid, _
                DevicePathName)

            'If there is at least one HID, attempt to read the Vendor ID and Product ID
            'of each device until there is a match or all devices have been examined.

            If DeviceFound = True Then
                MemberIndex = 0
                Do
                    '***
                    'API function:
                    'CreateFile

                    'Purpose:
                    'Retrieves a handle to a device.

                    'Accepts:
                    'A device path name returned by SetupDiGetDeviceInterfaceDetail
                    'The type of access requested (read/write).
                    'FILE_SHARE attributes to allow other processes to access the device while this handle is open.
                    'A Security structure. Using Null for this may cause problems under Windows XP.
                    'A creation disposition value. Use OPEN_EXISTING for devices.
                    'Flags and attributes for files. Not used for devices.
                    'Handle to a template file. Not used.

                    'Returns: a handle without read or write access.
                    'This enables obtaining information about all HIDs, even system
                    'keyboards and mice. 
                    'Separate handles are used for reading and writing.
                    '***

                    HIDHandle = CreateFile _
                        (DevicePathName(MemberIndex), _
                        0, _
                        FILE_SHARE_READ Or FILE_SHARE_WRITE, _
                        Security, _
                        OPEN_EXISTING, _
                        0, _
                        0)

                    Debug.WriteLine(MyDebugging.ResultOfAPICall("CreateFile"))
                    Debug.WriteLine("  Returned handle: " & Hex(HIDHandle) & "h")

                    If (HIDHandle <> INVALID_HANDLE_VALUE) Then

                        'The returned handle is valid, 
                        'so find out if this is the device we're looking for.

                        'Set the Size property of DeviceAttributes to the number of bytes in the structure.

                        MyHID.DeviceAttributes.Size = Marshal.SizeOf(MyHID.DeviceAttributes)

                        '***
                        'API function:
                        'HidD_GetAttributes

                        'Purpose:
                        'Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID, 
                        'Product ID, and Product Version Number for a device.

                        'Accepts:
                        'A handle returned by CreateFile.
                        'A pointer to receive a HIDD_ATTRIBUTES structure.

                        'Returns:
                        'True on success, False on failure.
                        '***

                        Result = HidD_GetAttributes(HIDHandle, MyHID.DeviceAttributes)


                        Debug.WriteLine(MyDebugging.ResultOfAPICall("HidD_GetAttributes"))

                        If Result Then

                            Debug.WriteLine("  HIDD_ATTRIBUTES structure filled without error.")

                            Debug.WriteLine("  Structure size: " & MyHID.DeviceAttributes.Size)

                            Debug.WriteLine("  Vendor ID: " & Hex(MyHID.DeviceAttributes.VendorID))
                            Debug.WriteLine("  Product ID: " & Hex(MyHID.DeviceAttributes.ProductID))
                            Debug.WriteLine("  Version Number: " & Hex(MyHID.DeviceAttributes.VersionNumber))

                            'Find out if the device matches the one we're looking for.

                            If (MyHID.DeviceAttributes.VendorID = MyVendorID) And _
                                (MyHID.DeviceAttributes.ProductID = MyProductID) Then

                                'It's the desired device.


                                Call ScrollToBottomOfListBox()

                                MyDeviceDetected = True

                                'Save the DevicePathName so OnDeviceChange() knows which name is my device.

                                MyDevicePathName = DevicePathName(MemberIndex)
                            Else

                                'It's not a match, so close the handle.

                                MyDeviceDetected = False

                                Result = CloseHandle(HIDHandle)

                                Debug.WriteLine(MyDebugging.ResultOfAPICall("CloseHandle"))
                            End If
                        Else
                            'There was a problem in retrieving the information.

                            Debug.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.")
                            MyDeviceDetected = False
                            Result = CloseHandle(HIDHandle)
                        End If

                    End If


                    'Keep looking until we find the device or there are no more left to examine.

                    MemberIndex = MemberIndex + 1

                Loop Until ((MyDeviceDetected = True) Or _
                    (MemberIndex = UBound(DevicePathName) + 1))
            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, _
                    HidGuid, _
                    DeviceNotificationHandle)

                Debug.WriteLine("RegisterForDeviceNotifications = " & Success)

                'Learn the capabilities of the device.

                MyHID.Capabilities = MyHID.GetDeviceCapabilities _
                    (HIDHandle)

                If Success Then

                    'Find out if the device is a system mouse or keyboard.

                    HIDUsage = MyHID.GetHIDUsage(MyHID.Capabilities)

                    'Get and display the Input report buffer size.

                    GetInputReportBufferSize()
                    cmdInputReportBufferSize.Enabled = True

                    'Get handles to use in requesting Input and Output reports.

                    ReadHandle = CreateFile _
                        (MyDevicePathName, _
                        GENERIC_READ, _
                        FILE_SHARE_READ Or FILE_SHARE_WRITE, _
                        Security, _
                        OPEN_EXISTING, _
                        FILE_FLAG_OVERLAPPED, _
                        0)

                    Debug.WriteLine(MyDebugging.ResultOfAPICall("CreateFile, ReadHandle"))
                    Debug.WriteLine("  Returned handle: " & Hex(ReadHandle) & "h")

                    If (ReadHandle = INVALID_HANDLE_VALUE) Then

                        ExclusiveAccess = True

                        Call ScrollToBottomOfListBox()

                    Else

                        WriteHandle = CreateFile _
                             (MyDevicePathName, _
                             GENERIC_WRITE, _
                             FILE_SHARE_READ Or FILE_SHARE_WRITE, _
                             Security, _
                             OPEN_EXISTING, _
                             0, _
                             0)

                        Debug.WriteLine(MyDebugging.ResultOfAPICall("CreateFile, WriteHandle"))
                        Debug.WriteLine("  Returned handle: " & Hex(WriteHandle) & "h")

                        '(optional)
                        'Flush any waiting reports in the input buffer.

                        MyHID.FlushQueue(ReadHandle)

                    End If

                End If

            Else

                'The device wasn't detected.

                cmdInputReportBufferSize.Enabled = False
                cmdOnce.Enabled = True

                Debug.WriteLine(" Device not found.")

                Call ScrollToBottomOfListBox()
            End If
            Return MyDeviceDetected

        Catch ex As Exception
            Call HandleException(Me.Name, ex)
        End Try
    End Function


    Private Sub AccessForm(ByVal action As String, ByVal formText As String)

        'Purpose    : In asynchronous ReadFiles, the callback function GetInputReportData  
        '           : uses this routine to access the application's Form, which runs in 

⌨️ 快捷键说明

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