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

📄 frmmain.cs

📁 usbio using microsoft visual c# example
💻 CS
📖 第 1 页 / 共 4 页
字号:
		private void GetInputReportData (IAsyncResult ar)
		{
			
			// Purpose    : Retrieves Input report data and status information.
			//            : This routine is called automatically when myInputReport.Read
			//            : returns.
			
			// Accepts    : ar - an object containing status information about
			//            : the asynchronous operation.
			
			string ByteValue;
			byte[] InputReportBuffer = new byte[0];
			bool Success = false;
			
			try
			{
				
				// Define a delegate using the IAsyncResult object.
				ReadInputReportDelegate deleg = ((ReadInputReportDelegate)(ar.AsyncState));
				
				// Get the IAsyncResult object and the values of other paramaters that the
				// BeginInvoke method passed ByRef.
				deleg.EndInvoke(ref _MyDeviceDetected, ref InputReportBuffer, ref Success, ar);
				
				// Display the received report data in the form's list box.
				if (ar.IsCompleted & Success) {
					
					lstResults.Items.Add("An Input report has been read.");
					
					Debug.WriteLine(" Input Report ID: " + InputReportBuffer[0]);
					Debug.WriteLine(" Input Report Data:");
					
					lstResults.Items.Add(" Input Report ID: " + InputReportBuffer[0]);
					lstResults.Items.Add(" Input Report Data:");
					
					txtBytesReceived.Text = "";
					for (int i = 0; i < InputReportBuffer.Length; i++) {
						
						// Add a leading zero to values from 0 to F.
						if (InputReportBuffer[i].ToString("x").Length < 2) {
							ByteValue = "0" + InputReportBuffer[i].ToString("x");
						} else {
							ByteValue = InputReportBuffer[i].ToString("x");
						}
						
						Debug.WriteLine(" " + ByteValue);
						lstResults.Items.Add(" " + ByteValue);
						
						// Display the report data in the "Received Data" text box.
						txtBytesReceived.SelectionStart = txtBytesReceived.Text.Length;
						txtBytesReceived.SelectedText = ByteValue + "\n";
					}
					
				} else {
					lstResults.Items.Add("The attempt to read an Input report has failed.");
					Debug.Write("The attempt to read an Input report has failed");
				}
				
				ScrollToBottomOfListBox();
				
				// Enable requesting another transfer.
				cmdOnce.Enabled = true;
				
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
			
		}
		
		
		private void GetVendorAndProductIDsFromTextBoxes (ref short myVendorID, ref short myProductID)
		{
			
			// Purpose    : Retrieves a Vendor ID and Product ID in hexadecimal
			//            : from the form's text boxes and converts the text to Shorts.
			// Accepts    : myVendorID - the Vendor ID as a Short.
			//            : myProductID - the Product ID as a Short.
      try {
        //myVendorID = System.Convert.ToInt16(Conversion.Val("&h" + txtVendorID.Text)) - 1107;
        //myProductID = System.Convert.ToInt16(Conversion.Val("&h" + txtProductID.Text)) - offp;
        myVendorID = short.Parse(txtVendorID.Text, System.Globalization.NumberStyles.HexNumber);
        myProductID = short.Parse(txtProductID.Text, System.Globalization.NumberStyles.HexNumber);
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
			
		}
		
		
		private void InitializeDisplay ()
		{
			
			// Purpose    : Initialize the elements on the form.
			
			string ByteValue;
			
			try {
				// Create a dropdown list box for each byte to send in a report.
				// Add a leading zero for values from 0 to F.
				for (int i = 0; i < 255; i++) {
					if (i.ToString("x").Length < 2) {
						ByteValue = "0" + i.ToString("x");
					} else {
						ByteValue = i.ToString("x");
					}
					this.cboByte0.Items.Insert(i, ByteValue);
				}
				
				for (int i = 0; i <= 255; i++) {
					if (i.ToString("x").Length < 2) {
						ByteValue = "0" + i.ToString("x");
					} else {
						ByteValue = i.ToString("x");
					}
					this.cboByte1.Items.Insert(i, ByteValue);
				}
				
				// Select a default value for each box
				this.cboByte0.SelectedIndex = 0;
				this.cboByte1.SelectedIndex = 128;
				
				// Check the autoincrement box to increment the values each time a report is sent.
				chkAutoincrement.CheckState = System.Windows.Forms.CheckState.Checked;
				
				// Don't allow the user to select an input report buffer size until there is
				// a handle to a HID.
				cmdInputReportBufferSize.Enabled = false;
				
				if (_MyHID.IsWindowsXpOrLater()) {
					
					chkUseControlTransfersOnly.Enabled = true;
					
				} else {
					// If the operating system is earlier than Windows XP,
					// disable the option to force Input and Output reports to use control transfers
					// (not supported).
					chkUseControlTransfersOnly.Enabled = false;
				}
				
				lstResults.Items.Add("For a more detailed event log, view debug statements in Visual Studio's Output window:");
				lstResults.Items.Add("Click Build > Configuration Manager > Active Solution Configuration > Debug.");
				lstResults.Items.Add("Then click View > Other Windows > Output.");
				lstResults.Items.Add("");
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
			
		}
		
		
		private void ReadAndWriteToDevice ()
		{
			
			// Purpose    : Initiates the exchanging of reports.
			//            : The application sends a report and requests to read a report.
			
			// Report header for the debug display:
			Debug.WriteLine("");
			Debug.WriteLine("***** HID Test Report *****");
			Debug.WriteLine(DateTime.Today + ": " + DateTime.Today.ToShortTimeString());
			
			try {
				// If the device hasn't been detected, was removed, or timed out on a previous attempt
				// to access it, look for the device.
				if (!_MyDeviceDetected) {
					_MyDeviceDetected = FindTheHid();
				}
				
				if (_MyDeviceDetected) {
					
					// Get the bytes to send in a report from the combo boxes.
					// Increment the values if the autoincrement check box is selected.
					if (chkAutoincrement.Checked) {
						if (cboByte0.SelectedIndex < 255) {
							cboByte0.SelectedIndex = cboByte0.SelectedIndex + 1;
						} else {
							cboByte0.SelectedIndex = 0;
						}
						if (cboByte1.SelectedIndex < 255) {
							cboByte1.SelectedIndex = cboByte1.SelectedIndex + 1;
						} else {
							cboByte1.SelectedIndex = 0;
						}
					}
					
					// An option button selects whether to exchange Input and Output reports
					// or Feature reports.
					if (optInputOutput.Checked) {
						ExchangeInputAndOutputReports();
					} else {
						ExchangeFeatureReports();
					}
				}
				
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
			
		}
		
		private void ScrollToBottomOfListBox ()
		{
			try {
				// Scroll to the bottom of the list box.
				lstResults.SelectedIndex = lstResults.Items.Count - 1;
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
		}
		
		private void SetInputReportBufferSize ()
		{
			
			// Purpose    : Set the number of Input buffers (the number of Input reports
			//            : the host will store) from the value in the text box.
			
			int NumberOfInputBuffers;
			
			try {
				// Get the number of buffers from the text box.
				NumberOfInputBuffers = int.Parse(txtInputReportBufferSize.Text);
				
				// Set the number of buffers.
				_MyHID.SetNumberOfInputBuffers(_HIDHandle, NumberOfInputBuffers);
				
				// Verify and display the result.
				GetInputReportBufferSize();
				
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
		}
		
		
		private void Shutdown ()
		{
			// Purpose    : Perform actions that must execute when the program ends.
			
			try {
				// Close open handles to the device.
				if (_HIDHandle != 0) {
					FileIOApiDeclarations.CloseHandle(_HIDHandle);
					Debug.WriteLine(_MyDebugging.ResultOfAPICall("CloseHandle (HIDHandle)"));
				}
				
				if (_ReadHandle != 0) {
					FileIOApiDeclarations.CloseHandle(_ReadHandle);
					Debug.WriteLine(_MyDebugging.ResultOfAPICall("CloseHandle (ReadHandle)"));
				}
				
				// Stop receiving notifications.
				_MyDeviceManagement.StopReceivingDeviceNotifications(_DeviceNotificationHandle);
				
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
			
		}
		
		
		private void Startup ()
		{
			// Purpose    : Perform actions that must execute when the program starts.
			
			try {
				_MyHID = new Hid();
				InitializeDisplay();
				tmrContinuousDataCollect.Enabled = false;
				tmrContinuousDataCollect.Interval = 1000;
				
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
			
		}
		
		
		private void tmrContinuousDataCollect_Tick (System.Object eventSender, System.EventArgs eventArgs)
		{
			
			try {
				// Exchange data with the device.
				// The timer is enabled only if cmdContinous has been clicked,
				// selecting continous (periodic) transfers.
				ReadAndWriteToDevice();
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
		}
		
		
		private void txtProductID_TextChanged (System.Object sender, System.EventArgs e)
		{
			// The Product ID has changed in the text box.
			
			try {
				DeviceHasChanged();
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
		}
		
		
		private void txtVendorID_TextChanged (System.Object sender, System.EventArgs e)
		{
			// The Vendor ID has changed in the text box.
			try {
				DeviceHasChanged();
			} catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
			
		}
		
		
		protected override void WndProc (ref Message m)
		{
			// Purpose    : Overrides WndProc to enable checking for and handling
			//            : WM_DEVICECHANGE(messages)
			// Accepts    : m - a Windows Message
			
			try {
				// The OnDeviceChange routine processes WM_DEVICECHANGE messages.
				if (m.Msg == DeviceManagementApiDeclarations.WM_DEVICECHANGE) {
					OnDeviceChange(m);
				}
				
				// Let the base form process the message.
				base.WndProc(ref m);
			
      } catch (Exception ex) {
				HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
			
		}
		
		
		static public void HandleException (string moduleName, Exception e)
		{
			// Purpose    : Provides a central mechanism for exception handling.
			//            : Displays a message box that describes the exception.
			// Accepts    : moduleName - the module where the exception occurred.
			//            : e - the exception
			string Message;
			string Caption;
			
			try {
				// Create an error message.
				Message = "Exception: " + e.Message + Environment.NewLine + "Module: " + moduleName + Environment.NewLine + "Method: " + e.TargetSite.Name;
				
				// Specify a caption.
				Caption = "Unexpected Exception";
				
				// Display the message in a message box.
				MessageBox.Show(Message, Caption, MessageBoxButtons.OK);
				Debug.Write(Message);
				
      } catch (Exception ex) {
        Debug.WriteLine ("HandleException: " + ex.Message);
      }
			
		}

		
	}
}

⌨️ 快捷键说明

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