public void RegisterForPnpEvents()
        {
            Win32Api.DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new Win32Api.DEV_BROADCAST_DEVICEINTERFACE();
            IntPtr devBroadcastDeviceInterfaceBuffer;
            IntPtr deviceNotificationHandle;

            System.Windows.Interop.HwndSource hwndSource = System.Windows.Interop.HwndSource.FromHwnd(new System.Windows.Interop.WindowInteropHelper(this).Handle);
            hwndSource.AddHook(new System.Windows.Interop.HwndSourceHook(WndProc));

            int size = Marshal.SizeOf(devBroadcastDeviceInterface);

            devBroadcastDeviceInterface.dbcc_size       = size;
            devBroadcastDeviceInterface.dbcc_devicetype = Win32Api.DBT_DEVTYP_DEVICEINTERFACE;
            devBroadcastDeviceInterface.dbcc_reserved   = 0;
            devBroadcastDeviceInterface.dbcc_classguid  = DEVICE_INTERFACE_GUID_STDFU;

            devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true);
            deviceNotificationHandle = Win32Api.RegisterDeviceNotification(hwndSource.Handle, devBroadcastDeviceInterfaceBuffer, Win32Api.DEVICE_NOTIFY_WINDOW_HANDLE);
            Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer);
        }
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            // Handle whatever Win32 message it is we feel like handling
            if (msg == Win32Api.WM_DEVICECHANGE)
            {
                if (wParam.ToInt32() == Win32Api.DBT_DEVICEARRIVAL)
                {
                    Win32Api.DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new Win32Api.DEV_BROADCAST_DEVICEINTERFACE();
                    Marshal.PtrToStructure(lParam, devBroadcastDeviceInterface);
                    OnDeviceArrival(devBroadcastDeviceInterface.dbcc_classguid, devBroadcastDeviceInterface.dbcc_name);
                }
                else if (wParam.ToInt32() == Win32Api.DBT_DEVICEREMOVECOMPLETE)
                {
                    Win32Api.DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new Win32Api.DEV_BROADCAST_DEVICEINTERFACE();
                    Marshal.PtrToStructure(lParam, devBroadcastDeviceInterface);
                    OnDeviceRemoveComplete(devBroadcastDeviceInterface.dbcc_classguid, devBroadcastDeviceInterface.dbcc_name);
                }
                handled = true;
            }

            return(IntPtr.Zero);
        }