public static IntPtr Register(IntPtr hRecipient, Guid classGuid, RegisterDeviceNotificationFlags flags)
        {
            var buffer = IntPtr.Zero;
            var handle = IntPtr.Zero;

            var notificationFilter = new DevBroadcastDeviceInterfaceStruct
            {
                DeviceType = (uint)Dbch_DeviceType.DBT_DEVTYP_DEVICEINTERFACE,
                Reserved = 0,
                ClassGuid = classGuid,
                Name = 0 //TODO: pass from arguments
            };
            notificationFilter.Size = Marshal.SizeOf(notificationFilter);

            try
            {
                buffer = Marshal.AllocHGlobal(notificationFilter.Size);
                Marshal.StructureToPtr(notificationFilter, buffer, true);

                handle = RegisterDeviceNotificationMethod(hRecipient, buffer, (uint)flags);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }

            return handle;
        }
        /// <summary>
        /// Registers a window to receive notifications when USB devices are plugged or unplugged.
        /// </summary>
        /// <param name="windowHandle">Handle to the window receiving notifications.</param>
        private static void RegisterUsbDeviceNotification(IntPtr windowHandle)
        {
            var dbi = new DevBroadcastDeviceinterface {
                DeviceType = DeviceType.DBT_DEVTYP_DEVICEINTERFACE,
                Reserved   = 0,
                Name       = 0,
                ClassGuid  = GUID_DEVINTERFACE_HID,                // not used when flags contains ALL_INTERFACE_CLASSES
            };

            dbi.Size = Marshal.SizeOf(dbi);
            IntPtr buffer = Marshal.AllocHGlobal(dbi.Size);

            Marshal.StructureToPtr(dbi, buffer, true);

            RegisterDeviceNotificationFlags flags =
                RegisterDeviceNotificationFlags.DEVICE_NOTIFY_WINDOW_HANDLE;

            _notificationHandle = RegisterDeviceNotification(windowHandle, buffer, flags);
        }
Beispiel #3
0
 internal static extern RegisterDeviceNotificationSafeHandle RegisterDeviceNotification_SafeHandle(
     IntPtr hRecipient,
     ref DEV_BROADCAST_HANDLE notificationFilter,
     RegisterDeviceNotificationFlags flags
     );
 private static extern IntPtr RegisterDeviceNotification(IntPtr recipient, IntPtr notificationFilter, RegisterDeviceNotificationFlags flags);