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

📄 frmmain.cs

📁 usbio using microsoft visual c# example
💻 CS
📖 第 1 页 / 共 5 页
字号:
						// 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 that enables reading and writing to the device.
						// ***
						
                        /*
                         * //GRV - this failed to detect device!!
						_HIDHandle = FileIOApiDeclarations.CreateFile
                (DevicePathName[MemberIndex], 
                 FileIOApiDeclarations.GENERIC_READ | FileIOApiDeclarations.GENERIC_WRITE, 
                 FileIOApiDeclarations.FILE_SHARE_READ | FileIOApiDeclarations.FILE_SHARE_WRITE, 
                 ref Security, 
                 FileIOApiDeclarations.OPEN_EXISTING,
                 0,
                 0);
                         */

                        //GRV - this works and is a true copy of Axelson
                        _HIDHandle = FileIOApiDeclarations.CreateFile
                (DevicePathName[MemberIndex],
                 0,
                 FileIOApiDeclarations.FILE_SHARE_READ | FileIOApiDeclarations.FILE_SHARE_WRITE,
                 ref Security,
                 FileIOApiDeclarations.OPEN_EXISTING,
                 0,
                 0);						


						Debug.WriteLine(_MyDebugging.ResultOfAPICall("CreateFile"));
						Debug.WriteLine("  Returned handle: " + _HIDHandle.ToString("x") + "h");
						
						if (_HIDHandle != FileIOApiDeclarations.INVALID_HANDLE_VALUE) {
							
							// 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 = _MyHID.DeviceAttributes.ToString().Length;
              _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 = HidApiDeclarations.HidD_GetAttributes(_HIDHandle, ref _MyHID.DeviceAttributes);
							
							
							Debug.WriteLine(_MyDebugging.ResultOfAPICall("HidD_GetAttributes"));
							
							if (Result != 0) {
								
								Debug.WriteLine("  HIDD_ATTRIBUTES structure filled without error.");
								
								//Debug.WriteLine("  Structure size: " + MyHID.DeviceAttributes.Size);
								Debug.WriteLine("  Vendor ID: " + _MyHID.DeviceAttributes.VendorID.ToString("x"));
								Debug.WriteLine("  Product ID: " + _MyHID.DeviceAttributes.ProductID.ToString("x"));
								Debug.WriteLine("  Version Number: " + _MyHID.DeviceAttributes.VersionNumber.ToString("x"));
								
								// Find out if the device matches the one we're looking for.
								if ((_MyHID.DeviceAttributes.VendorID == MyVendorID) & 
                                    (_MyHID.DeviceAttributes.ProductID == MyProductID)) {
									
									// It's the desired device.
									Debug.WriteLine("  My device detected");
									
									// Display the information in form's list box.
									lstResults.Items.Add("Device detected:");
									lstResults.Items.Add("  Vendor ID = " + _MyHID.DeviceAttributes.VendorID.ToString("x"));
									lstResults.Items.Add("  Product ID = " + _MyHID.DeviceAttributes.ProductID.ToString("x"));
									
									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 = FileIOApiDeclarations.CloseHandle(_HIDHandle);
									
									Debug.WriteLine(_MyDebugging.ResultOfAPICall("CloseHandle"));
								}
							} else {
								// There was a problem in retrieving the information.
								Debug.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.");
								_MyDeviceDetected = false;
								Result = FileIOApiDeclarations.CloseHandle(_HIDHandle);
							}
						}
						
						// Keep looking until we find the device or there are no more left to examine.
						MemberIndex = MemberIndex + 1;
						
					} while (!((_MyDeviceDetected == true) |(MemberIndex == DevicePathName.Length))); //GRV - +1 deleted per Axelson
				}
				
				if (_MyDeviceDetected) {
					
					// The device was detected.
					// Register to receive notifications if the device is removed or attached.
					Success = _MyDeviceManagement.RegisterForDeviceNotifications
                        (_MyDevicePathName,
                        this.Handle,
                        HidGuid,
                        ref _DeviceNotificationHandle);
					
					Debug.WriteLine("RegisterForDeviceNotifications = " + Success);
					
					// Learn the capabilities of the device.
					_MyHID.Capabilities = _MyHID.GetDeviceCapabilities(_HIDHandle);
                    
                    //GRV - show report size in GUI
                    lblFeatureRepLength.Text = "Length: " + (_MyHID.Capabilities.FeatureReportByteLength - 1).ToString();
					
					if (Success) {
                        //Find out if device is system mouse or keyboard //GRV
                        HIDUsage = _MyHID.GetHIDUsage(_MyHID.Capabilities);
                        

						// Get and display the Input report buffer size.
						GetInputReportBufferSize();
						cmdInputReportBufferSize.Enabled = true;
						

                        //GRV - mod
						// Get another handle to use in overlapped ReadFiles (for requesting Input reports).
						_ReadHandle = FileIOApiDeclarations.CreateFile
                            (_MyDevicePathName,
                            FileIOApiDeclarations.GENERIC_READ,
                            FileIOApiDeclarations.FILE_SHARE_READ | FileIOApiDeclarations.FILE_SHARE_WRITE,
                            ref Security,
                            FileIOApiDeclarations.OPEN_EXISTING,
                            FileIOApiDeclarations.FILE_FLAG_OVERLAPPED, 0);
						
						Debug.WriteLine(_MyDebugging.ResultOfAPICall("CreateFile, ReadHandle"));
						Debug.WriteLine("  Returned handle: " + _ReadHandle.ToString("x") + "h");


                        //GRV - added
                        if (_ReadHandle == FileIOApiDeclarations.INVALID_HANDLE_VALUE)
                        {
                            _ExclusiveAccess = true;
                            lstResults.Items.Add("The device is a system " + HIDUsage + ".");
                            lstResults.Items.Add("W2K & XP obtain exclusive access to Input & Output reports for this device.");
                            lstResults.Items.Add("Applications can access feature reports only");
                            ScrollToBottomOfListBox();
                        }
                        else
                        {
                            _WriteHandle=FileIOApiDeclarations.CreateFile
                            (_MyDevicePathName,
                            FileIOApiDeclarations.GENERIC_WRITE,
                            FileIOApiDeclarations.FILE_SHARE_READ | FileIOApiDeclarations.FILE_SHARE_WRITE,
                            ref Security,
                            FileIOApiDeclarations.OPEN_EXISTING,
                            0,
                            0);
                        }

						// (optional)
						// Flush any waiting reports in the input buffer.
						_MyHID.FlushQueue(_ReadHandle);
					}
				} else {
					
					// The device wasn't detected.
					lstResults.Items.Add("Device not found.");
					cmdInputReportBufferSize.Enabled = false;
					cmdOnce.Enabled = true;
					
					Debug.WriteLine(" Device not found.");
					
					ScrollToBottomOfListBox();
				}
				
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
      return _MyDeviceDetected;
    }
		

		//GRV - added
        private void AccessForm(string action, string formText)
            
        //Purpose    : In asynchronous ReadFiles, the callback function GetInputReportData  
        //           : 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.

        //Accepts    : action - a string that names the action to perform on the form
        //           : formText - text that the form displays or the code uses for 
        //           : another purpose. Actions that don't use text ignore this parameter.  
        {
            switch (action)
            {
                case "AddItemToListBox":
                    lstResults.Items.Add(formText);
                    break;

                case "AddItemToTextBox":
                    txtBytesReceived.SelectedText = formText + "\r\n";
                    break;
                case "EnableCmdOnce":
                    cmdOnce.Enabled = true;
                    break;
                case "ScrollToBottomOfListBox":
                    lstResults.SelectedIndex = lstResults.Items.Count - 1;
                    break;
                case "TextBoxSelectionStart":
                    txtBytesReceived.SelectionStart = formText.Length;
                    break;

            }


        }


		private void cmdContinuous_Click (System.Object eventSender, System.EventArgs eventArgs)
		{
			
			// Start or stop a series of periodic transfers.
			try
			{
				if (cmdContinuous.Text == "Continuous") {
					
					// Start doing periodic transfers.
					// Change the command button to "Cancel Continuous"
					cmdContinuous.Text = "Cancel Continuous";
					
					// Enable the timer event to trigger a set of transfers.
					tmrContinuousDataCollect.Enabled = true;
					ReadAndWriteToDevice();
				} else {
					
					// Stop doing continuous transfers.
					// Change the command button to "Continuous"
					cmdContinuous.Text = "Continuous";
					
					// Disable the timer that triggers the transfers.
					tmrContinuousDataCollect.Enabled = false;
				}
				
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
		}
		
		
		private void cmdInputReportBufferSize_Click (System.Object sender, System.EventArgs e)
		{
			
			// Set the number of Input reports the host will store.
			try {
				SetInputReportBufferSize();
				
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
		}
		
		
		private void cmdFindDevice_Click (System.Object sender, System.EventArgs e)
		{
			
			// Search for a specific device.
			try {
				FindTheHid();
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
			
		}
		
		
		private void cmdOnce_Click (System.Object eventSender, System.EventArgs eventArgs)

⌨️ 快捷键说明

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