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

📄 devicemanagement.cs

📁 usbio using microsoft visual c# example
💻 CS
📖 第 1 页 / 共 2 页
字号:
                IntPtr.Zero, 0, ref BufferSize, IntPtr.Zero);
						
            Debug.WriteLine(MyDebugging.ResultOfAPICall("SetupDiGetDeviceInterfaceDetail"));
						Debug.WriteLine("  (OK to say too small)");
						Debug.WriteLine("  Required buffer size for the data: " + BufferSize);
						
						// Store the structure's size.
            //MyDeviceInterfaceDetailData.cbSize = MyDeviceInterfaceDetailData.ToString().Length;
            MyDeviceInterfaceDetailData.cbSize = Marshal.SizeOf(MyDeviceInterfaceDetailData);
						
						// Allocate memory for the MyDeviceInterfaceDetailData Structure using the returned buffer size.
						IntPtr DetailDataBuffer = Marshal.AllocHGlobal(BufferSize);
						
						// Store cbSize in the first 4 bytes of the array
						Marshal.WriteInt32(DetailDataBuffer, 4 + Marshal.SystemDefaultCharSize);
						Debug.WriteLine("cbsize = " + MyDeviceInterfaceDetailData.cbSize);
						
						// Call SetupDiGetDeviceInterfaceDetail again.
						// This time, pass a pointer to DetailDataBuffer
						// and the returned required buffer size.
						Success = DeviceManagementApiDeclarations.SetupDiGetDeviceInterfaceDetail (
                DeviceInfoSet, 
                ref MyDeviceInterfaceData, 
                DetailDataBuffer, 
                BufferSize, 
                ref BufferSize, 
                IntPtr.Zero);
						
						Debug.WriteLine(MyDebugging.ResultOfAPICall(" Result of second call: "));
						Debug.WriteLine("  MyDeviceInterfaceDetailData.cbSize: " + MyDeviceInterfaceDetailData.cbSize.ToString());
						
						// Skip over cbsize (4 bytes) to get the address of the devicePathName.
						IntPtr pdevicePathName = new IntPtr(DetailDataBuffer.ToInt32() + 4);
						
						// Get the String containing the devicePathName.
						SingledevicePathName = Marshal.PtrToStringAuto(pdevicePathName);
						devicePathName[MemberIndex] = SingledevicePathName;
						
						Debug.WriteLine("Device Path = " + devicePathName[MemberIndex]);
            //Debug.WriteLine("Device Path Length= " + Marshal.SizeOf(devicePathName[MemberIndex]));
            Debug.WriteLine("Device Path Length = " + devicePathName[MemberIndex].Length);
						
						// Free the memory allocated previously by AllocHGlobal.
						Marshal.FreeHGlobal(DetailDataBuffer);
						DeviceFound = true;
					}
					MemberIndex++;
				} while (!LastDevice);
				
				// Trim the array to the number of devices found.
				Debug.WriteLine("Number of HIDs found = " + (MemberIndex - 1).ToString());
				
				// ***
				// API function:
				// SetupDiDestroyDeviceInfoList
				// Purpose:
				// Frees the memory reserved for the DeviceInfoSet returned by SetupDiGetClassDevs.
				// Accepts:
				// A DeviceInfoSet returned by SetupDiGetClassDevs.
				// Returns:
				// True on success, False on failure.
				// ***
				
				Result = DeviceManagementApiDeclarations.SetupDiDestroyDeviceInfoList(DeviceInfoSet);
				
				Debug.WriteLine(MyDebugging.ResultOfAPICall("DestroyDeviceInfoList"));
				
			}	catch (Exception ex) {
				HandleException(ModuleName + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
      
      return DeviceFound;
		}
		
		
		internal bool RegisterForDeviceNotifications (string devicePathName, IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle)
		{
			
			// Purpose    : Request to receive a notification when a device is attached or removed.
			
			// Accepts    : devicePathName - a handle to a device.
			//            : formHandle - a handle to the window that will receive device events.
			//            : classGuid - an interface class GUID.
			// 
			
			// Returns    : True on success, False on failure.
			
			// A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request.
			DeviceManagementApiDeclarations.DEV_BROADCAST_DEVICEINTERFACE DevBroadcastDeviceInterface = new DeviceManagementApiDeclarations.DEV_BROADCAST_DEVICEINTERFACE();
			IntPtr DevBroadcastDeviceInterfaceBuffer;
			
			int size;
			
			try
			{
				// Set the parameters in the DEV_BROADCAST_DEVICEINTERFACE structure.
				
				// Set the size.
        size = Marshal.SizeOf(DevBroadcastDeviceInterface);
        DevBroadcastDeviceInterface.dbcc_size = size;
				
				// Request to receive notifications about a class of devices.
				DevBroadcastDeviceInterface.dbcc_devicetype = DeviceManagementApiDeclarations.DBT_DEVTYP_DEVICEINTERFACE;
				
				DevBroadcastDeviceInterface.dbcc_reserved = 0;
				
				// Specify the interface class to receive notifications about.
				DevBroadcastDeviceInterface.dbcc_classguid = classGuid;
				
				// Allocate memory for the buffer that holds the DEV_BROADCAST_DEVICEINTERFACE structure.
				DevBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size);
				
				// Copy the DEV_BROADCAST_DEVICEINTERFACE structure to the buffer.
				// Set fDeleteOld True to prevent memory leaks.
				Marshal.StructureToPtr(DevBroadcastDeviceInterface, DevBroadcastDeviceInterfaceBuffer, true);
				
				// ***
				// API function:
				// RegisterDeviceNotification
				// Purpose:
				// Request to receive notification messages when a device in an interface class
				// is attached or removed.
				// Accepts:
				// Aa handle to the window that will receive device events
				// A pointer to a DEV_BROADCAST_DEVICEINTERFACE to specify the type of
				// device to send notifications for,
				// DEVICE_NOTIFY_WINDOW_HANDLE to indicate that Handle is a window handle.
				// Returns:
				// A device notification handle or NULL on failure.
				// ***
				
				deviceNotificationHandle = DeviceManagementApiDeclarations.RegisterDeviceNotification(formHandle, DevBroadcastDeviceInterfaceBuffer, DeviceManagementApiDeclarations.DEVICE_NOTIFY_WINDOW_HANDLE);
				
				// Marshal data from the unmanaged block DevBroadcastDeviceInterfaceBuffer to
				// the managed object DevBroadcastDeviceInterface
				Marshal.PtrToStructure(DevBroadcastDeviceInterfaceBuffer, DevBroadcastDeviceInterface);
				
				// Free the memory allocated previously by AllocHGlobal.
				Marshal.FreeHGlobal(DevBroadcastDeviceInterfaceBuffer);
				
				// Find out if RegisterDeviceNotification was successful.
				if (deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32()) {
					Debug.WriteLine("RegisterDeviceNotification error");
					return false;
				}
				
			} catch (Exception ex) {
				HandleException(ModuleName + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
			}
      
      return true;
    }
		
		
		internal void StopReceivingDeviceNotifications (IntPtr deviceNotificationHandle)
		{
			
			// Purpose    : Requests to stop receiving notification messages when a device in an
			//              interface class is attached or removed.
			// Accepts    : deviceNotificationHandle - a handle returned previously by
			//              RegisterDeviceNotification
			
			try {
				
				// ***
				// API function: UnregisterDeviceNotification
				// Purpose: Stop receiving notification messages.
				// Accepts: a handle returned previously by RegisterDeviceNotification
				// Returns: True on success, False on failure.
				// ***
				
				// Ignore failures.
				DeviceManagementApiDeclarations.UnregisterDeviceNotification(deviceNotificationHandle);
				
			} catch (Exception ex) {
				HandleException(ModuleName + ":" + 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);
			} finally { }
		
    }
		
	}
	
}

⌨️ 快捷键说明

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