public RegisterDeviceNotifications(IntPtr hWnd, Guid gCat) { category = gCat; var di = new DEV_BROADCAST_DEVICEINTERFACE(); // Register to be notified of events of category gCat di.dbcc_size = Marshal.SizeOf(di); di.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; di.dbcc_classguid = gCat; hdevnotify = RegisterDeviceNotification( hWnd, di, DEVICE_NOTIFY_WINDOW_HANDLE ); // If it failed, throw an exception if (hdevnotify == IntPtr.Zero) { var i = unchecked((int)0x80070000); i += Marshal.GetLastWin32Error(); throw new COMException("Failed to RegisterDeviceNotifications", i); } }
/// <summary> /// Hook the device class to a <see cref="DevicesMonitor" /> instance. /// </summary> /// <param name="hWnd">A handle to the window or service that will receive device events</param> /// <param name="isServiceHandle">Indicate whether <see cref="hWnd"/> parameter is a window handle or service status handle</param> /// <param name="deviceId">Device GUID. See <see cref="DeviceGuids"/> for a list of predefined GUID values</param> public void Register(IntPtr hWnd, bool isServiceHandle, Guid deviceId) { if (hWnd.IsInvalidHandle()) { throw new InvalidOperationException("Invalid window handle."); } if (!_notificationHandle.IsInvalidHandle()) { throw new InvalidOperationException($"{GetType().Name} is already attached."); } DEV_BROADCAST_DEVICEINTERFACE di = new DEV_BROADCAST_DEVICEINTERFACE { DeviceType = DBT_DeviceType.DeviceInterface, ClassGuid = deviceId }; di.Size = Marshal.SizeOf(di); _notificationData = Marshal.AllocHGlobal(di.Size); Marshal.StructureToPtr(di, _notificationData, true); int flags = isServiceHandle ? Win32.DEVICE_NOTIFY_SERVICE_HANDLE : Win32.DEVICE_NOTIFY_WINDOW_HANDLE; if (deviceId.IsEmpty()) { flags |= Win32.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES; } _notificationHandle = Win32.RegisterDeviceNotification(hWnd, _notificationData, flags); }
public static void HookHardwareNotifications(IntPtr callback, bool UseWindowHandle) { try { DEV_BROADCAST_DEVICEINTERFACE dbdi = new DEV_BROADCAST_DEVICEINTERFACE(); dbdi.dbcc_size = (uint)Marshal.SizeOf(dbdi); dbdi.dbcc_reserved = 0; dbdi.dbcc_devicetype = (uint)DBT_DEVTYP.DBT_DEVTYP_DEVICEINTERFACE; if (UseWindowHandle) { NativeMethods.RegisterDeviceNotification( callback, dbdi, DEVICE_NOTIFY.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES | DEVICE_NOTIFY.DEVICE_NOTIFY_WINDOW_HANDLE); } else { NativeMethods.RegisterDeviceNotification( callback, dbdi, DEVICE_NOTIFY.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES | DEVICE_NOTIFY.DEVICE_NOTIFY_WINDOW_HANDLE); } } catch (Exception ex) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Error calling RegisterDeviceNotification"); } }
public RemoveQueryHook(char driveLetter, IntPtr windowHandle) { mDriveLetter = driveLetter; DEV_BROADCAST_DEVICEINTERFACE data = new DEV_BROADCAST_DEVICEINTERFACE(); data.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; data.dbcc_name = '\0'; // This GUID is for all USB serial host PnP drivers, but you can replace it // with any valid device class guid. data.dbcc_classguid = new Guid(0x25dbce51, 0x6c8f, 0x4a72, 0x8a, 0x6d, 0xb5, 0x4c, 0x2b, 0x4f, 0xc8, 0x35); int size = Marshal.SizeOf(data); data.dbcc_size = (uint)size; IntPtr buffer = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(data, buffer, true); mRegisterDeviceHandle = Native.RegisterDeviceNotification(windowHandle, buffer, 0); if (mRegisterDeviceHandle == IntPtr.Zero) { throw new Exception("RegisterDeviceNotification() failed on drive '" + mDriveLetter.ToString() + "'"); } } finally { Marshal.FreeHGlobal(buffer); } }
private void OnWmDeviceChange(UIntPtr wParam, IntPtr lParam) { DEV_BROADCAST_HDR dbh = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_HDR)); if (dbh.dbch_devicetype != DBT_DEVTYP_DEVICEINTERFACE) { return; } DEV_BROADCAST_DEVICEINTERFACE dbi = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_DEVICEINTERFACE)); UInt32 eventType = wParam.ToUInt32(); if (DBT_DEVICEARRIVAL == eventType) { if (this.DeviceConnected != null) { this.DeviceConnected(this, new DeviceManagementNotificationsEventArgs(true, dbi.dbcc_classguid, dbi.dbcc_name)); } } else if (DBT_DEVICEREMOVECOMPLETE == eventType) { if (this.DeviceDisconnected != null) { this.DeviceDisconnected(this, new DeviceManagementNotificationsEventArgs(false, dbi.dbcc_classguid, dbi.dbcc_name)); } } }
public Boolean Start(Guid classGuid) { if (!this.CreateWindow()) { return(false); } DEV_BROADCAST_DEVICEINTERFACE dbi = new DEV_BROADCAST_DEVICEINTERFACE { dbch_devicetype = DBT_DEVTYP_DEVICEINTERFACE, dbch_reserved = 0, dbcc_classguid = classGuid, dbcc_name = "" }; dbi.dbch_size = (UInt32)Marshal.SizeOf(dbi); IntPtr buffer = Marshal.AllocHGlobal((int)dbi.dbch_size); Marshal.StructureToPtr(dbi, buffer, true); this.notificationHandle = RegisterDeviceNotification(this.WindowHandle, buffer, 0); if (IntPtr.Zero == this.notificationHandle) { Tracer.Trace("RegisterDeviceNotification failed with error {0}", Marshal.GetLastWin32Error()); return(false); } return(true); }
public bool RegisterForDeviceChange(bool Register, Form f) { bool Status = false; if (Register) { DEV_BROADCAST_DEVICEINTERFACE deviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); int size = Marshal.SizeOf(deviceInterface); deviceInterface.dbcc_size = size; deviceInterface.dbcc_devicetype = (int)DBTDEVTYP.DBT_DEVTYP_DEVICEINTERFACE; IntPtr buffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(deviceInterface, buffer, true); deviceEventHandle = RegisterDeviceNotification(f.Handle, buffer, Convert.ToInt32(DEVICE_NOTIFY.DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES)); Status = deviceEventHandle != IntPtr.Zero; Marshal.FreeHGlobal(buffer); } else { if (deviceEventHandle != IntPtr.Zero) { Status = UnregisterDeviceNotification(deviceEventHandle); } deviceEventHandle = IntPtr.Zero; } return(Status); }
public static bool TryPtrToDeviceInfo(IntPtr handle, out UsbDeviceInfo deviceInfo) { bool Result = false; deviceInfo = null; try { DEV_BROADCAST_HDR header = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(handle, typeof(DEV_BROADCAST_HDR)); if (header.DeviceType == DBT.DEVTYP_DEVICEINTERFACE) { DEV_BROADCAST_DEVICEINTERFACE devInterface = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(handle, typeof(DEV_BROADCAST_DEVICEINTERFACE)); var broadcastName = devInterface.Name; var friendlyName = GetDeviceFriendlyName(broadcastName); deviceInfo = new UsbDeviceInfo { Name = broadcastName, ClassGuid = devInterface.ClassGuid, FriendlyName = friendlyName, }; Result = true; } } catch (Exception ex) { logger.Error(ex); } return(Result); }
public static bool RegisterNotify(IntPtr form, Guid Class, ref IntPtr handle, bool window = true) { var devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; try { var devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); var size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = Class; devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); handle = RegisterDeviceNotification(form, devBroadcastDeviceInterfaceBuffer, window ? DEVICE_NOTIFY_WINDOW_HANDLE : DEVICE_NOTIFY_SERVICE_HANDLE); Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); return(handle != IntPtr.Zero); } catch (Exception ex) { Log.ErrorFormat("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
IntPtr hwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == WM_DEVICECHANGE) { if ((int)wParam == DBT_DEVICEARRIVAL) { DEV_BROADCAST_DEVICEINTERFACE info = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_DEVICEINTERFACE)); if (info.dbcc_classguid == HidClassGuid) { if (SUDDriver.DescribeSUD(info.dbcc_name).ProductType == SeneyeProductType.SUDv2e) { this.MessageBus.SendMessage <string>(info.dbcc_name, "SUDArrived"); } } } else if ((int)wParam == DBT_DEVICEREMOVECOMPLETE) { DEV_BROADCAST_DEVICEINTERFACE info = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_DEVICEINTERFACE)); if (info.dbcc_classguid == HidClassGuid) { this.MessageBus.SendMessage <string>(info.dbcc_name, "HIDDisconnected"); } } } return(IntPtr.Zero); }
/// <summary> /// Constructor. Creates a message-only window to receive notifications when devices are plugged or unplugged and calls a function specified by a delegate. /// </summary> /// <param name="windowHandle">Handle to the window receiving notifications.</param> /// <param name="usbOnly">true to filter to USB devices only, false to be notified for all devices.</param> public DeviceNotification(IntPtr windowHandle, bool usbOnly) { // Define the filter for device notifications which contains information about a class of devices. var deviceBroadcastInterface = new DEV_BROADCAST_DEVICEINTERFACE { deviceType = DBT_DEVTYP_DEVICEINTERFACE, reserved = 0, classGuid = GUID_DEVINTERFACE_USB_DEVICE, name = 0 }; // Retrieve the size for this filter struct. deviceBroadcastInterface.size = Unsafe.SizeOf <DEV_BROADCAST_DEVICEINTERFACE>(); // Allocate a buffer in unmanaged memory with the size of the filter. IntPtr buffer = Marshal.AllocHGlobal(deviceBroadcastInterface.size); // Marshal the DEV_BROADCAST_DEVICEINTERFACE structure into unmanaged memory. unsafe { Unsafe.Write((void *)buffer, deviceBroadcastInterface); } // Register the notification handle for the message only window to receive controller connect/disconnect notifications. _notificationHandle = RegisterDeviceNotification(windowHandle, buffer, usbOnly ? 0 : DEVICE_NOTIFY_ALL_INTERFACE_CLASSES); }
public RegisterDeviceNotifications(IntPtr hWnd, Guid gCat) { m_Category = gCat; DEV_BROADCAST_DEVICEINTERFACE di = new DEV_BROADCAST_DEVICEINTERFACE(); // Register to be notified of events of category gCat di.dbcc_size = Marshal.SizeOf(di); di.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; di.dbcc_classguid = gCat; m_hdevnotify = RegisterDeviceNotification( hWnd, di, DEVICE_NOTIFY_WINDOW_HANDLE ); // If it failed, throw an exception if (m_hdevnotify == IntPtr.Zero) { int i = unchecked ((int)0x80070000); i += Marshal.GetLastWin32Error(); throw new COMException("Failed to RegisterDeviceNotifications", i); } }
// Static routine to parse out the device type from the IntPtr received in WndProc public bool CheckEventDetails(IntPtr pReason, IntPtr pHdr) { int iValue = pReason.ToInt32(); // Check the event type if (iValue != DBT_DEVICEREMOVECOMPLETE && iValue != DBT_DEVICEARRIVAL) { return(false); } // Do we have device details yet? if (pHdr == IntPtr.Zero) { return(false); } // Parse the first chunk DEV_BROADCAST_HDR pBH = new DEV_BROADCAST_HDR(); Marshal.PtrToStructure(pHdr, pBH); // Check the device type if (pBH.dbch_devicetype != DBT_DEVTYP_DEVICEINTERFACE) { return(false); } // Only parse this if the right device type DEV_BROADCAST_DEVICEINTERFACE pDI = new DEV_BROADCAST_DEVICEINTERFACE(); Marshal.PtrToStructure(pHdr, pDI); return(pDI.dbcc_classguid == m_Category); }
/// <summary> /// Registers to device events. /// </summary> /// <param name="serviceHandle">Service status handle</param> /// <param name="classGuid">Device interface class Guid</param> /// <returns>Device notification handle</returns> public static IntPtr Register(IntPtr serviceHandle, Guid classGuid) { var dbcc = new DEV_BROADCAST_DEVICEINTERFACE { dbcc_size = (uint)Marshal.SizeOf <DEV_BROADCAST_DEVICEINTERFACE>(), dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE, dbcc_classguid = classGuid }; var buffer = IntPtr.Zero; try { buffer = Marshal.AllocHGlobal((int)dbcc.dbcc_size); Marshal.StructureToPtr(dbcc, buffer, true); return(RegisterDeviceNotification( serviceHandle, buffer, DEVICE_NOTIFY_SERVICE_HANDLE)); } catch (Exception ex) { Debug.WriteLine($"Failed to register.\r\n{ex}"); return(IntPtr.Zero); } finally { if (buffer != IntPtr.Zero) { Marshal.FreeHGlobal(buffer); } } }
public Boolean Start(Guid classGuid) { if (!this.CreateWindow()) { return false; } DEV_BROADCAST_DEVICEINTERFACE dbi = new DEV_BROADCAST_DEVICEINTERFACE { dbch_devicetype = DBT_DEVTYP_DEVICEINTERFACE, dbch_reserved = 0, dbcc_classguid = classGuid, dbcc_name = "" }; dbi.dbch_size = (UInt32)Marshal.SizeOf(dbi); IntPtr buffer = Marshal.AllocHGlobal((int)dbi.dbch_size); Marshal.StructureToPtr(dbi, buffer, true); this.notificationHandle = RegisterDeviceNotification(this.WindowHandle, buffer, 0); if (IntPtr.Zero == this.notificationHandle) { Tracer.Trace("RegisterDeviceNotification failed with error {0}", Marshal.GetLastWin32Error()); return false; } return true; }
public static string GetDeviceName(DEV_BROADCAST_DEVICEINTERFACE dvi) { string[] Parts = dvi.dbcc_name.Split('#'); if (Parts.Length >= 3) { string DevType = Parts[0].Substring(Parts[0].IndexOf(@"?\") + 2); string DeviceInstanceId = Parts[1]; string DeviceUniqueID = Parts[2]; string RegPath = @"SYSTEM\CurrentControlSet\Enum\" + DevType + "\\" + DeviceInstanceId + "\\" + DeviceUniqueID; RegistryKey key = Registry.LocalMachine.OpenSubKey(RegPath); if (key != null) { object result = key.GetValue("FriendlyName"); if (result != null) { return(result.ToString()); } result = key.GetValue("DeviceDesc"); if (result != null) { return(result.ToString()); } } } return(String.Empty); }
/// <summary> /// 当设备插入或拔出时请求接收消息 /// Requests to receive a notification when a device is attached or removed. /// </summary> /// <param name="devicePathName"> 设备句柄 handle to a device. </param> /// <param name="formHandle"> 接收事件的窗体句柄 handle to the window that will receive device events. </param> /// <param name="classGuid"> 设备接口 GUID device interface GUID. </param> /// <param name="deviceNotificationHandle"> 返回设备事件句柄 returned device notification handle. </param> /// <returns> /// 成功返回True /// </returns> public Boolean RegisterForDeviceNotifications(String devicePathName, IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) { // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; 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 = 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函数 deviceNotificationHandle = RegisterDeviceNotification(formHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); Debug.WriteLine("在函数RegisterForDeviceNotifications中" + this.MyDebugging.ResultOfAPICall("RegisterDeviceNotification")); // 从非管理的devBroadcastDeviceInterfaceBuffer数据块集合到受管理的devBroadcastDeviceInterface对象 // Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to the managed object devBroadcastDeviceInterface Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); if ((deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32())) { return(false); } else { return(true); } } catch (Exception) { throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { // 释放由AllocHGlobal函数分配的内存空间。 Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
/// <summary> /// registerForDeviceNotification - registers the window (identified by the windowHandle) for /// device notification messages from Windows /// </summary> public Boolean registerForDeviceNotifications(IntPtr windowHandle) { Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> Method called"); // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; // Get the required GUID System.Guid systemHidGuid = new Guid(); HidD_GetHidGuid(ref systemHidGuid); try { // Set the parameters in the DEV_BROADCAST_DEVICEINTERFACE structure. size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = systemHidGuid; devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); // Register for notifications and store the returned handle deviceInformation.deviceNotificationHandle = RegisterDeviceNotification(windowHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); if ((deviceInformation.deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32())) { Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> Notification registration failed"); return(false); } else { Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> Notification registration succeded"); return(true); } } catch (Exception) { Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> EXCEPTION: An unknown exception has occured!"); } finally { // Free the memory allocated previously by AllocHGlobal. if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } return(false); }
private static DeviceEventInfo TransformDeviceEvent(ref Message m) { var tm = new DeviceEventInfo { DEVICEEVENT = (ServicesAPI.SERVICE_CONTROL_DEVICEEVENT_Control)(int) m.WParam }; DEV_BROADCAST_HDR dbh = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR)); tm.DeviceType = dbh.dbch_devicetype; switch (dbh.dbch_devicetype) { case dbch_devicetype.DBT_DEVTYP_DEVICEINTERFACE: DEV_BROADCAST_DEVICEINTERFACE dbdi = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_DEVICEINTERFACE)); tm.DeviceId = cstr_to_string(dbdi.dbcc_name); tm.DeviceName = ConvertDbccNameToFriendlyName(cstr_to_string(dbdi.dbcc_name)); break; case dbch_devicetype.DBT_DEVTYP_HANDLE: DEV_BROADCAST_HANDLE dbbh = (DEV_BROADCAST_HANDLE)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HANDLE)); tm.DeviceName = "Handle Id " + dbbh.dbch_handle.ToString(); break; case dbch_devicetype.DBT_DEVTYP_OEM: DEV_BROADCAST_OEM dbo = (DEV_BROADCAST_OEM)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_OEM)); tm.DeviceName = string.Format("OEM: {0} Value: {1}", dbo.dbco_identifier, dbo.dbco_suppfunc); break; case dbch_devicetype.DBT_DEVTYP_PORT: DEV_BROADCAST_PORT dbp = (DEV_BROADCAST_PORT)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_PORT)); IntPtr pData = (IntPtr)(m.LParam.ToInt32() + dbp.dbcp_size); // (*1) IntPtr offsetDbcpName = Marshal.OffsetOf(typeof(DEV_BROADCAST_PORT), "dbcp_name"); int len = (int)pData - (int)offsetDbcpName; tm.DeviceName = Marshal.PtrToStringAuto(offsetDbcpName, len); break; case dbch_devicetype.DBT_DEVTYP_VOLUME: DEV_BROADCAST_VOLUME dbv = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME)); tm.DeviceName = dbv.dbcv_unitmask.ToString(); if (dbv.dbcv_flags != dbcv_flags.None) { tm.DeviceName += " " + dbv.dbcv_flags.ToString(); } break; } //dbh.dbch_devicetype == dbch_devicetype. //IntPtr pData = (IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(ps)); // (*1) return(tm); }
private void TestStructure(IntPtr lParam) { DEV_BROADCAST_HDR hdr = Marshal.PtrToStructure <DEV_BROADCAST_HDR>(lParam); if (hdr.deviceType == DeviceType.DeviceInterface) { Console.WriteLine("DBT_DEVTYP_DEVICEINTERFACE"); DEV_BROADCAST_DEVICEINTERFACE device = Marshal.PtrToStructure <DEV_BROADCAST_DEVICEINTERFACE>(lParam); IntPtr offsetPtr = new IntPtr(lParam.ToInt32() + sizeof(int) * 3 + Marshal.SizeOf <Guid>()); string name = Marshal.PtrToStringAuto(offsetPtr); Console.WriteLine(name); } }
internal bool RegisterForDeviceNotification(IntPtr devHandle, ref IntPtr devNotificationHandle) { //Globally Unique Identifier (GUID). Windows uses GUIDs to identify things. Guid InterfaceClassGuid = new Guid(0xa5dcbf10, 0x6530, 0x11d2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED); //Globally Unique Identifier (GUID) for USB peripheral devices // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; 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 = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; // Specify the interface class to receive notifications about. devBroadcastDeviceInterface.dbcc_classguid = InterfaceClassGuid; // 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); devNotificationHandle = RegisterDeviceNotification(devHandle, devBroadcastDeviceInterfaceBuffer, 0); if (devNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32()) { return(false); } else { return(true); } } catch { throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
public static string GetDeviceInfo(DEV_BROADCAST_DEVICEINTERFACE dvi) { string[] Parts = dvi.dbcc_name.Split('#'); if (Parts.Length >= 3) { string DevType = Parts[0].Substring(Parts[0].IndexOf(@"?\") + 2); string DeviceInstanceId = Parts[1]; string DeviceUniqueID = Parts[2]; Guid deviceGuid; if (Parts.Length > 3) { deviceGuid = Guid.Parse(Parts[3]); } } return(String.Empty); }
public void Start() { DEV_BROADCAST_DEVICEINTERFACE notificationFilter = new DEV_BROADCAST_DEVICEINTERFACE(); int size = Marshal.SizeOf(notificationFilter); notificationFilter.dbcc_size = size; notificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; notificationFilter.dbcc_reserved = 0; notificationFilter.dbcc_classguid = new Guid(HIDClassID).ToByteArray(); IntPtr buffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(notificationFilter, buffer, true); IntPtr result = RegisterDeviceNotification(Handle, buffer, (Int32)(DEVICE_NOTIFY.DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES)); }
public static void RegisterDeviceNotification(IntPtr windowHandle) { var dbi = new DEV_BROADCAST_DEVICEINTERFACE { dbcc_devicetype = DbtDevtypDeviceinterface, dbcc_reserved = 0, dbcc_classguid = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED") }; dbi.dbcc_size = Marshal.SizeOf(dbi); IntPtr buffer = Marshal.AllocHGlobal(dbi.dbcc_size); Marshal.StructureToPtr(dbi, buffer, true); notificationHandle = RegisterDeviceNotification(windowHandle, buffer, DEVICE_NOTIFY_ALL_INTERFACE_CLASSES); }
public void Register() { this._hwndSource.AddHook(new HwndSourceHook(this.hwndSourceHook)); DEV_BROADCAST_DEVICEINTERFACE notificationFilter = new DEV_BROADCAST_DEVICEINTERFACE(); int size = Marshal.SizeOf(notificationFilter); notificationFilter.dbcc_size = size; notificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; notificationFilter.dbcc_reserved = 0; notificationFilter.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE; // HidClassGuid; IntPtr buffer = IntPtr.Zero; buffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(notificationFilter, buffer, true); IntPtr result = NativeMethods.RegisterDeviceNotification(this._hwndSource.Handle, buffer, (Int32)(DEVICE_NOTIFY.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES)); }
public MyControl() { //Register for WM_DEVICECHANGE notifications. This code uses these messages to detect plug and play connection/disconnection events for USB devices DEV_BROADCAST_DEVICEINTERFACE DeviceBroadcastHeader = new DEV_BROADCAST_DEVICEINTERFACE(); DeviceBroadcastHeader.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; DeviceBroadcastHeader.dbcc_size = (uint)Marshal.SizeOf(DeviceBroadcastHeader); DeviceBroadcastHeader.dbcc_reserved = 0; //Reserved says not to use... DeviceBroadcastHeader.dbcc_classguid = InterfaceClassGuid; //Need to get the address of the DeviceBroadcastHeader to call RegisterDeviceNotification(), but //can't use "&DeviceBroadcastHeader". Instead, using a roundabout means to get the address by //making a duplicate copy using Marshal.StructureToPtr(). IntPtr pDeviceBroadcastHeader = IntPtr.Zero; //Make a pointer. pDeviceBroadcastHeader = Marshal.AllocHGlobal(Marshal.SizeOf(DeviceBroadcastHeader)); //allocate memory for a new DEV_BROADCAST_DEVICEINTERFACE structure, and return the address Marshal.StructureToPtr(DeviceBroadcastHeader, pDeviceBroadcastHeader, false); //Copies the DeviceBroadcastHeader structure into the memory already allocated at DeviceBroadcastHeaderWithPointer RegisterDeviceNotification(this.Handle, pDeviceBroadcastHeader, DEVICE_NOTIFY_WINDOW_HANDLE); }
/// <summary> /// Registers your form to receive notifications from Windows when one /// of a particular class of devices is removed or attached. /// </summary> /// <param name="deviceInterfaceGuid">The device interface GUID from the INF file.</param> /// <param name="formHandle">The handle of the form that will receive notifications (form.Handle).</param> /// <returns>A handle representing this notification request.</returns> internal static unsafe IntPtr notificationRegister(Guid deviceInterfaceGuid, IntPtr formHandle) { DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); devBroadcastDeviceInterface.dbcc_size = (UInt32)sizeof(DEV_BROADCAST_DEVICEINTERFACE); devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_classguid = deviceInterfaceGuid; IntPtr deviceNotificationHandle = RegisterDeviceNotification(formHandle, &devBroadcastDeviceInterface, DEVICE_NOTIFY_WINDOW_HANDLE); if (deviceNotificationHandle == IntPtr.Zero) { throw new Win32Exception("There was an error registering for device attachment/removal notifications."); } return(deviceNotificationHandle); }
// 注册USB设备 增/删 处理消息 internal Boolean RegisterForDeviceNotifications(IntPtr formHandle, ref IntPtr deviceNotificationHandle) { DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; try { size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; //devBroadcastDeviceInterface.dbcc_classguid = classGuid; devBroadcastDeviceInterface.dbcc_classguid = Guid.Empty; devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); deviceNotificationHandle = RegisterDeviceNotification(formHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); if ((deviceNotificationHandle.ToInt64() == IntPtr.Zero.ToInt64())) { return(false); } else { return(true); } } catch (Exception) { throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { // 释放内存 Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
/// <param name="windowHandle">Handle to the window receiving notifications.</param> /// <param name="usbOnly">true to filter to USB devices only, false to be notified for all devices.</param> public unsafe DeviceNotification(IntPtr windowHandle, bool usbOnly) { // Define filter. var deviceBroadcastInterface = new DEV_BROADCAST_DEVICEINTERFACE { deviceType = Native.DBT_DEVTYP_DEVICEINTERFACE, reserved = 0, classGuid = Native.GUID_DEVINTERFACE_USB_DEVICE, name = 0, size = Unsafe.SizeOf <DEV_BROADCAST_DEVICEINTERFACE>() }; // Manually marshal filter to unmanaged memory. _buffer = Marshal.AllocHGlobal(deviceBroadcastInterface.size); Unsafe.Write((void *)_buffer, deviceBroadcastInterface); // Register for device notifications. _notificationHandle = Native.RegisterDeviceNotification(windowHandle, _buffer, usbOnly ? 0 : Native.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES); }
public static void RegisterDeviceNotification_All(IntPtr handle) { var dbi = new DEV_BROADCAST_DEVICEINTERFACE(); int size = Marshal.SizeOf(dbi); dbi.dbcc_size = size; dbi.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; dbi.dbcc_reserved = 0; dbi.dbcc_classguid = GUID_DEVINTERFACE_HID; dbi.dbcc_name = 0; IntPtr buffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(dbi, buffer, true); IntPtr result = RegisterDeviceNotification( handle, buffer, DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES); if (result == IntPtr.Zero) { Console.WriteLine(GetLastError().ToString()); #if DEBUG Debugger.Break(); #endif } // dbi.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE; // buffer = Marshal.AllocHGlobal(size); // Marshal.StructureToPtr(dbi, buffer, true); // result = RegisterDeviceNotification( // handle, // buffer, // DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES); // if (result == IntPtr.Zero) // { // Console.WriteLine(GetLastError().ToString()); //#if DEBUG // Debugger.Break(); //#endif // } }
private void RegisterUSBDeviceNotification(IntPtr windowHandle) { DEV_BROADCAST_DEVICEINTERFACE dbi = new DEV_BROADCAST_DEVICEINTERFACE { DeviceType = DBT_DEVTYP_DEVICEINTERFACE, Reserved = 0, ClassGuid = _interfaceGuid, Name = 0 }; dbi.Size = (UInt32)Marshal.SizeOf(dbi); _notificationFilterBuffer = Marshal.AllocHGlobal((int)dbi.Size); Marshal.StructureToPtr(dbi, _notificationFilterBuffer, false); _notificationHandle = RegisterDeviceNotification(windowHandle, _notificationFilterBuffer, 0); if (_notificationHandle == INVALID_HANDLE_VALUE) { WirekiteException.ThrowWin32Exception("Registration of device notification failed"); } }
private void RegisterUsbDeviceNotification(IntPtr windowHandle) { var dbcc = new DEV_BROADCAST_DEVICEINTERFACE { dbcc_size = (uint)Marshal.SizeOf(typeof(DEV_BROADCAST_DEVICEINTERFACE)), dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE, dbcc_classguid = DsHidMiniDriver.DeviceInterfaceGuid }; var notificationFilter = Marshal.AllocHGlobal(Marshal.SizeOf(dbcc)); Marshal.StructureToPtr(dbcc, notificationFilter, true); _notificationHandle = RegisterDeviceNotification(windowHandle, notificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); if (_notificationHandle == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to register device notifications."); } }
//--------------- End of Global Varibles ------------------ //-------------------------------------------------------END CUT AND PASTE BLOCK------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------------------------------------------------------- //Need to check "Allow unsafe code" checkbox in build properties to use unsafe keyword. Unsafe is needed to //properly interact with the unmanged C++ style APIs used to find and connect with the USB device. public unsafe Form1() { InitializeComponent(); //------------------------------------------------------------------------------------------------------------------------------------------------------------------- //-------------------------------------------------------BEGIN CUT AND PASTE BLOCK----------------------------------------------------------------------------------- //Additional constructor code //Initialize tool tips, to provide pop up help when the mouse cursor is moved over objects on the form. ANxVoltageToolTip.SetToolTip(this.ANxVoltage_lbl, "If using a board/PIM without a potentiometer, apply an adjustable voltage to the I/O pin."); ANxVoltageToolTip.SetToolTip(this.progressBar1, "If using a board/PIM without a potentiometer, apply an adjustable voltage to the I/O pin."); ToggleLEDToolTip.SetToolTip(this.ToggleLEDs_btn, "Sends a packet of data to the USB device."); PushbuttonStateTooltip.SetToolTip(this.PushbuttonState_lbl, "Try pressing pushbuttons on the USB demo board/PIM."); //Register for WM_DEVICECHANGE notifications. This code uses these messages to detect plug and play connection/disconnection events for USB devices DEV_BROADCAST_DEVICEINTERFACE DeviceBroadcastHeader = new DEV_BROADCAST_DEVICEINTERFACE(); DeviceBroadcastHeader.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; DeviceBroadcastHeader.dbcc_size = (uint)Marshal.SizeOf(DeviceBroadcastHeader); DeviceBroadcastHeader.dbcc_reserved = 0; //Reserved says not to use... DeviceBroadcastHeader.dbcc_classguid = InterfaceClassGuid; //Need to get the address of the DeviceBroadcastHeader to call RegisterDeviceNotification(), but //can't use "&DeviceBroadcastHeader". Instead, using a roundabout means to get the address by //making a duplicate copy using Marshal.StructureToPtr(). IntPtr pDeviceBroadcastHeader = IntPtr.Zero; //Make a pointer. pDeviceBroadcastHeader = Marshal.AllocHGlobal(Marshal.SizeOf(DeviceBroadcastHeader)); //allocate memory for a new DEV_BROADCAST_DEVICEINTERFACE structure, and return the address Marshal.StructureToPtr(DeviceBroadcastHeader, pDeviceBroadcastHeader, false); //Copies the DeviceBroadcastHeader structure into the memory already allocated at DeviceBroadcastHeaderWithPointer RegisterDeviceNotification(this.Handle, pDeviceBroadcastHeader, DEVICE_NOTIFY_WINDOW_HANDLE); //Now make an initial attempt to find the USB device, if it was already connected to the PC and enumerated prior to launching the application. //If it is connected and present, we should open read and write handles to the device so we can communicate with it later. //If it was not connected, we will have to wait until the user plugs the device in, and the WM_DEVICECHANGE callback function can process //the message and again search for the device. if(CheckIfPresentAndGetUSBDevicePath()) //Check and make sure at least one device with matching VID/PID is attached { uint ErrorStatusWrite; uint ErrorStatusRead; //We now have the proper device path, and we can finally open read and write handles to the device. WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); ErrorStatusWrite = (uint)Marshal.GetLastWin32Error(); ReadHandleToUSBDevice = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); ErrorStatusRead = (uint)Marshal.GetLastWin32Error(); if((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS)) { AttachedState = true; //Let the rest of the PC application know the USB device is connected, and it is safe to read/write to it AttachedButBroken = false; StatusBox_txtbx.Text = "Device Found, AttachedState = TRUE"; } else //for some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully... { AttachedState = false; //Let the rest of this application known not to read/write to the device. AttachedButBroken = true; //Flag so that next time a WM_DEVICECHANGE message occurs, can retry to re-open read/write pipes if(ErrorStatusWrite == ERROR_SUCCESS) WriteHandleToUSBDevice.Close(); if(ErrorStatusRead == ERROR_SUCCESS) ReadHandleToUSBDevice.Close(); } } else //Device must not be connected (or not programmed with correct firmware) { AttachedState = false; AttachedButBroken = false; } if (AttachedState == true) { StatusBox_txtbx.Text = "Device Found, AttachedState = TRUE"; } else { StatusBox_txtbx.Text = "Device not found, verify connect/correct firmware"; } ReadWriteThread.RunWorkerAsync(); //Recommend performing USB read/write operations in a separate thread. Otherwise, //the Read/Write operations are effectively blocking functions and can lock up the //user interface if the I/O operations take a long time to complete. //-------------------------------------------------------END CUT AND PASTE BLOCK------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------------------------------------------------------- }
public static IntPtr RegisterDeviceInterface(IntPtr hwnd, DeviceNotifyType notificationType, Guid device) { DebugLogger.WriteLine("Registering {0}", device); DEV_BROADCAST_DEVICEINTERFACE devInt = new DEV_BROADCAST_DEVICEINTERFACE(); devInt.dbcc_devicetype = dbch_devicetype.DBT_DEVTYP_DEVICEINTERFACE; devInt.dbcc_classguid = device.ToByteArray(); devInt.dbcc_size = Marshal.SizeOf(devInt); IntPtr buffer = Marshal.AllocHGlobal(devInt.dbcc_size); try { Marshal.StructureToPtr(devInt, buffer, false); return RegisterDeviceNotification(hwnd, buffer, notificationType); //| DeviceNotifyType.DEVICE_NOTIFY_SERVICE_HANDLE } finally { Marshal.FreeHGlobal(buffer); } }
public static bool RegisterNotify(IntPtr form, Guid Class, ref IntPtr handle, bool window = true) { var devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; try { var devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); var size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = Class; devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); handle = RegisterDeviceNotification(form, devBroadcastDeviceInterfaceBuffer, window ? DEVICE_NOTIFY_WINDOW_HANDLE : DEVICE_NOTIFY_SERVICE_HANDLE); Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); return handle != IntPtr.Zero; } catch (Exception ex) { Log.ErrorFormat("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
private void OnDeviceInterfaceChanged(DeviceEvent eventType, Message message, DEV_BROADCAST_HDR broadcastHeader) { int stringSize = Convert.ToInt32((broadcastHeader.dbch_size - 32) / 2); var deviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); Array.Resize(ref deviceInterface.dbcc_name, stringSize); Marshal.PtrToStructure(message.LParam, deviceInterface); var classId = new Guid(deviceInterface.dbcc_classguid); var deviceName = new string(deviceInterface.dbcc_name, 0, stringSize); Debug.Print("Hardware.OnDeviceInterfaceChanged(): {0} {2} {1}", eventType, deviceName, classId); var eh = DeviceInterfaceChanged; if (eh != null) { eh(this, new DeviceInterfaceChangedArgs(eventType, classId, deviceName)); } }
public static Boolean RegisterNotify(IntPtr Form, Guid Class, ref IntPtr Handle, Boolean Window = true) { IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; try { DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); Int32 Size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = Size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = Class; devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(Size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); Handle = RegisterDeviceNotification(Form, devBroadcastDeviceInterfaceBuffer, Window ? DEVICE_NOTIFY_WINDOW_HANDLE : DEVICE_NOTIFY_SERVICE_HANDLE); Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); return Handle != IntPtr.Zero; } catch (Exception ex) { Console.WriteLine("{0} {1}", ex.HelpLink, ex.Message); throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
private void RegisterNotifications(IntPtr hWnd) { var deviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); deviceInterface.dbcc_size = Marshal.SizeOf(deviceInterface); deviceInterface.dbcc_devicetype = (int)DeviceType.DeviceInterface; deviceInterface.dbcc_reserved = 0; deviceInterface.dbcc_classguid = new byte[16]; IntPtr pointer = Marshal.AllocHGlobal(deviceInterface.dbcc_size); Marshal.StructureToPtr(deviceInterface, pointer, true); const int flags = DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES; _notificationHandle = RegisterDeviceNotification(hWnd, pointer, flags); Marshal.FreeHGlobal(pointer); }
bool DeviceNameMatch(System.Windows.Forms.Message m, String mydevicePathName) { // The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure, // which is really a longer structure underneath // DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR(); Marshal.PtrToStructure(m.LParam, devBroadcastHeader); // if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)) { DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); Marshal.PtrToStructure(m.LParam, devBroadcastDeviceInterface); return String.Compare(devBroadcastDeviceInterface.dbcc_name, mydevicePathName, true) == 0; } return false; }
private void Form1_Load(object sender, EventArgs e) { // Register device notification in Form_Load HidD_GetHidGuid(ref myGuid); frmMy = this; DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer; Int32 size = 0; size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = myGuid; devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); deviceNotificationHandle = RegisterDeviceNotification(frmMy.Handle, devBroadcastDeviceInterfaceBuffer, (DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES)); Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); }
public static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, DEV_BROADCAST_DEVICEINTERFACE filter, int Flags);
/// <summary> /// Requests to receive a notification when a device is attached or removed. /// </summary> /// /// <param name="devicePathName"> handle to a device. </param> /// <param name="formHandle"> handle to the window that will receive device events. </param> /// <param name="classGuid"> device interface GUID. </param> /// <param name="deviceNotificationHandle"> returned device notification handle. </param> /// /// <returns> /// True on success. /// </returns> /// internal Boolean RegisterForDeviceNotifications(String devicePathName, IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) { // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; 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 = 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 // summary // Request to receive notification messages when a device in an interface class // is attached or removed. // parameters // Handle to the window that will receive device events. // Pointer to a DEV_BROADCAST_DEVICEINTERFACE to specify the type of // device to send notifications for. // DEVICE_NOTIFY_WINDOW_HANDLE indicates the handle is a window handle. // Returns // Device notification handle or NULL on failure. // *** deviceNotificationHandle = RegisterDeviceNotification(formHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); // Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to // the managed object devBroadcastDeviceInterface Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); if ((deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32())) { return false; } else { return true; } } catch { throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
public static void RegisterForDeviceNotifications(IntPtr controlHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) { DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; try { int size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = classGuid; 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); deviceNotificationHandle = RegisterDeviceNotification(controlHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); if (deviceNotificationHandle == IntPtr.Zero) throw APIException.Win32("Failed to register device notification"); // Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to // the managed object devBroadcastDeviceInterface Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); } finally { // Free the memory allocated previously by AllocHGlobal. if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } }
private static string GetDeviceNameNew(DEV_BROADCAST_DEVICEINTERFACE dvi) { string[] Parts = dvi.dbcc_name.Split('#'); if (Parts.Length >= 3) { string DevType = Parts[0].Substring(Parts[0].IndexOf(@"?\") + 2); string DeviceInstanceId = Parts[1]; string DeviceUniqueID = Parts[2]; string RegPath = @"SYSTEM\CurrentControlSet\Enum\" + DevType + "\\" + DeviceInstanceId + "\\" + DeviceUniqueID; RegistryKey key = Registry.LocalMachine.OpenSubKey(RegPath); if (key != null) { object result = key.GetValue("FriendlyName"); if (result != null) { Console.WriteLine("\tNEW Name: {0}", result.ToString()); return result.ToString(); } result = key.GetValue("DeviceDesc"); if (result != null) { Console.WriteLine("\tNEW Desc: {0}", result.ToString()); return result.ToString(); } } } return String.Empty; }
static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, ref DEV_BROADCAST_DEVICEINTERFACE NotificationFilter, uint Flags);
// Static routine to parse out the device type from the IntPtr received in WndProc public bool CheckEventDetails(IntPtr pReason, IntPtr pHdr) { var iValue = pReason.ToInt32(); // Check the event type if (iValue != DBT_DEVICEREMOVECOMPLETE && iValue != DBT_DEVICEARRIVAL) return false; // Do we have device details yet? if (pHdr == IntPtr.Zero) return false; // Parse the first chunk var pbh = new DEV_BROADCAST_HDR(); Marshal.PtrToStructure(pHdr, pbh); // Check the device type if (pbh.dbch_devicetype != DBT_DEVTYP_DEVICEINTERFACE) return false; // Only parse this if the right device type var pdi = new DEV_BROADCAST_DEVICEINTERFACE(); Marshal.PtrToStructure(pHdr, pdi); return (pdi.dbcc_classguid == category); }
public MainForm() { InitializeComponent(); //Register for WM_DEVICECHANGE notifications. This code uses these messages to detect plug and play connection/disconnection events for USB devices DEV_BROADCAST_DEVICEINTERFACE DeviceBroadcastHeader = new DEV_BROADCAST_DEVICEINTERFACE(); DeviceBroadcastHeader.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; DeviceBroadcastHeader.dbcc_size = (uint)Marshal.SizeOf(DeviceBroadcastHeader); DeviceBroadcastHeader.dbcc_reserved = 0; //Reserved says not to use... DeviceBroadcastHeader.dbcc_classguid = InterfaceClassGuid; //Need to get the address of the DeviceBroadcastHeader to call RegisterDeviceNotification(), but //can't use "&DeviceBroadcastHeader". Instead, using a roundabout means to get the address by //making a duplicate copy using Marshal.StructureToPtr(). IntPtr pDeviceBroadcastHeader = IntPtr.Zero; //Make a pointer. pDeviceBroadcastHeader = Marshal.AllocHGlobal(Marshal.SizeOf(DeviceBroadcastHeader)); //allocate memory for a new DEV_BROADCAST_DEVICEINTERFACE structure, and return the address Marshal.StructureToPtr(DeviceBroadcastHeader, pDeviceBroadcastHeader, false); //Copies the DeviceBroadcastHeader structure into the memory already allocated at DeviceBroadcastHeaderWithPointer RegisterDeviceNotification(this.Handle, pDeviceBroadcastHeader, DEVICE_NOTIFY_WINDOW_HANDLE); if (USBCheckIfPresentAndGetUSBDevicePath()) //Check and make sure at least one device with matching VID/PID is attached { uint ErrorStatusWrite; uint ErrorStatusRead; //We now have the proper device path, and we can finally open read and write handles to the device. WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); ErrorStatusWrite = (uint)Marshal.GetLastWin32Error(); ReadHandleToUSBDevice = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); ErrorStatusRead = (uint)Marshal.GetLastWin32Error(); if ((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS)) { AttachedState = true; //Let the rest of the PC application know the USB device is connected, and it is safe to read/write to it AttachedButBroken = false; StatusBar.Text = cnc_connected; } else //for some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully... { AttachedState = false; //Let the rest of this application known not to read/write to the device. AttachedButBroken = true; //Flag so that next time a WM_DEVICECHANGE message occurs, can retry to re-open read/write pipes if (ErrorStatusWrite == ERROR_SUCCESS) WriteHandleToUSBDevice.Close(); if (ErrorStatusRead == ERROR_SUCCESS) ReadHandleToUSBDevice.Close(); } } else //Device must not be connected (or not programmed with correct firmware) { AttachedState = false; AttachedButBroken = false; } if (AttachedState == true) { StatusBar.Text = cnc_connected; } else { StatusBar.Text = cnc_not_connected; } ReadWriteThread.RunWorkerAsync(); }
/// <summary> /// Requests to receive a notification when a device is attached or removed. /// </summary> /// /// <param name="formHandle"> handle to the window that will receive device events. </param> /// <param name="classGuid"> device interface GUID. </param> /// <param name="deviceNotificationHandle"> returned device notification handle. </param> /// /// <returns> /// True on success. /// </returns> internal Boolean RegisterForDeviceNotifications(IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) { // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; try { // Set the parameters in the DEV_BROADCAST_DEVICEINTERFACE structure. // Set the size of this structure size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; // Request to receive notifications about a class of devices. devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; // Reserved; do not use. 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. We are then ready to call the API function. Set fDeleteOld True to prevent memory leaks. Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); // Call deviceNotificationHandle to request to receive notification messages when a device in an interface class is attached or removed. deviceNotificationHandle = RegisterDeviceNotification(formHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); // Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to the managed object devBroadcastDeviceInterface Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); if ((deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32())) return false; else return true; } catch (Exception) { throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
/// <summary> /// registerForDeviceNotification - registers the window (identified by the windowHandle) for /// device notification messages from Windows /// </summary> public Boolean registerForDeviceNotifications(IntPtr windowHandle) { Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> Method called"); // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; // Get the required GUID System.Guid systemHidGuid = new Guid(); HidD_GetHidGuid(ref systemHidGuid); try { // Set the parameters in the DEV_BROADCAST_DEVICEINTERFACE structure. size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = systemHidGuid; devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); // Register for notifications and store the returned handle deviceInformation.deviceNotificationHandle = RegisterDeviceNotification(windowHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); if ((deviceInformation.deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32())) { Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> Notification registration failed"); return false; } else { Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> Notification registration succeded"); return true; } } catch (Exception) { Debug.WriteLine("usbGenericHidCommunication:registerForDeviceNotifications() -> EXCEPTION: An unknown exception has occured!"); } finally { // Free the memory allocated previously by AllocHGlobal. if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } return false; }
private void RegisterForDeviceNotifications() { DEV_BROADCAST_DEVICEINTERFACE devBDI = new DEV_BROADCAST_DEVICEINTERFACE(); devBDI.dbcc_size = Marshal.SizeOf(devBDI); devBDI.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBDI.dbcc_reserved = 0; devBDI.dbcc_classguid = guidNxtMindstormsDeviceInstance; devBDI.dbcc_name = ""; IntPtr hwnd = Program.TheForm.Handle; this.hDeviceNotify = RegisterDeviceNotification(hwnd, devBDI, DEVICE_NOTIFY_WINDOW_HANDLE); if (IntPtr.Zero == this.hDeviceNotify) ThrowWin32Error(); Program.TheForm.DeviceRemoveComplete += OnDeviceRemoveComplete; }
public RemoveQueryHook( char driveLetter, IntPtr windowHandle ) { mDriveLetter = driveLetter; DEV_BROADCAST_DEVICEINTERFACE data = new DEV_BROADCAST_DEVICEINTERFACE(); data.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; data.dbcc_name = '\0'; // This GUID is for all USB serial host PnP drivers, but you can replace it // with any valid device class guid. data.dbcc_classguid = new Guid( 0x25dbce51, 0x6c8f, 0x4a72, 0x8a, 0x6d, 0xb5, 0x4c, 0x2b, 0x4f, 0xc8, 0x35 ); int size = Marshal.SizeOf( data ); data.dbcc_size = (uint)size; IntPtr buffer = Marshal.AllocHGlobal( size ); try { Marshal.StructureToPtr( data, buffer, true ); mRegisterDeviceHandle = Native.RegisterDeviceNotification( windowHandle, buffer, 0 ); if ( mRegisterDeviceHandle == IntPtr.Zero ) throw new Exception( "RegisterDeviceNotification() failed on drive '" + mDriveLetter.ToString() + "'" ); } finally { Marshal.FreeHGlobal( buffer ); } }
internal bool RegisterForDeviceNotification(IntPtr devHandle, ref IntPtr devNotificationHandle) { //Globally Unique Identifier (GUID). Windows uses GUIDs to identify things. Guid InterfaceClassGuid = new Guid(0xa5dcbf10, 0x6530, 0x11d2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED); //Globally Unique Identifier (GUID) for USB peripheral devices // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; 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 = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; // Specify the interface class to receive notifications about. devBroadcastDeviceInterface.dbcc_classguid = InterfaceClassGuid; // 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); devNotificationHandle = RegisterDeviceNotification(devHandle, devBroadcastDeviceInterfaceBuffer, 0); if (devNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32()) { return false; } else { return true; } } catch { throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
private void RegisterForDeviceNotifications() { Log.Debug("Main: Registering for Device Notifications"); var devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); int size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; IntPtr devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); _deviceNotificationHandle = RegisterDeviceNotification(Handle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES); if (_deviceNotificationHandle == IntPtr.Zero) { Log.Warn("Main: Could not register for device notifications"); } }
protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_CREATE: try { DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer; IntPtr deviceNotificationHandle = IntPtr.Zero; Int32 size = 0; // frmMy is the form that will receive device-change messages. size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; devBroadcastDeviceInterface.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE.ToByteArray(); devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); deviceNotificationHandle = NativeMethods.RegisterDeviceNotification(this.Handle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); } catch { } break; case WM_DEVICECHANGE: // The WParam value identifies what is occurring. WM_DEVICECHANGE_enum n = (WM_DEVICECHANGE_enum)m.WParam; int l = (int)m.LParam; if (n == WM_DEVICECHANGE_enum.DBT_DEVICEREMOVEPENDING) { Console.WriteLine("DBT_DEVICEREMOVEPENDING"); } if (n == WM_DEVICECHANGE_enum.DBT_DEVNODES_CHANGED) { Console.WriteLine("DBT_DEVNODES_CHANGED"); } if (n == WM_DEVICECHANGE_enum.DBT_DEVICEARRIVAL || n == WM_DEVICECHANGE_enum.DBT_DEVICEREMOVECOMPLETE) { Console.WriteLine(((WM_DEVICECHANGE_enum)n).ToString()); DEV_BROADCAST_HDR hdr = new DEV_BROADCAST_HDR(); Marshal.PtrToStructure(m.LParam, hdr); try { switch (hdr.dbch_devicetype) { case DBT_DEVTYP_DEVICEINTERFACE: DEV_BROADCAST_DEVICEINTERFACE inter = new DEV_BROADCAST_DEVICEINTERFACE(); Marshal.PtrToStructure(m.LParam, inter); log.InfoFormat("Interface {0}", ASCIIEncoding.Unicode.GetString(inter.dbcc_name, 0, inter.dbcc_size - (4 * 3))); break; case DBT_DEVTYP_PORT: DEV_BROADCAST_PORT prt = new DEV_BROADCAST_PORT(); Marshal.PtrToStructure(m.LParam, prt); log.InfoFormat("port {0}", ASCIIEncoding.Unicode.GetString(prt.dbcp_name, 0, prt.dbcp_size - (4 * 3))); break; } } catch { } //string port = Marshal.PtrToStringAuto((IntPtr)((long)m.LParam + 12)); //Console.WriteLine("Added port {0}",port); } log.InfoFormat("Device Change {0} {1} {2}", m.Msg, (WM_DEVICECHANGE_enum)m.WParam, m.LParam); if (DeviceChanged != null) { try { DeviceChanged((WM_DEVICECHANGE_enum)m.WParam); } catch { } } foreach (Plugin.Plugin item in MissionPlanner.Plugin.PluginLoader.Plugins) { item.Host.ProcessDeviceChanged((WM_DEVICECHANGE_enum)m.WParam); } break; default: break; } base.WndProc(ref m); }
/// <summary> /// Request to receive a notification when a device is attached or removed. /// </summary> /// /// <param name="devicePathName"> a handle to a device.</param> /// <param name="formHandle"> a handle to the window that will receive device events. </param> /// <param name="classGuid"> an interface class GUID. </param> /// <param name="deviceNotificationHandle"> the retrieved handle. (Used when /// requesting to stop receiving notifications.) </param> /// /// <returns> /// True on success, False on failure. /// </returns> public Boolean RegisterForDeviceNotifications(String devicePathName, IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) { // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE DevBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = new System.IntPtr(); Int32 size = 0; 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 = 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: // A 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 = RegisterDeviceNotification( formHandle, devBroadcastDeviceInterfaceBuffer, 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; } else { return true; } } catch ( Exception ex ) { DisplayException( MODULE_NAME, ex ); throw ; } }