private void UnregisterDeviceNotification(IntPtr deviceHandle, IntPtr fileHandle) { if (DeviceHandles.ContainsKey(deviceHandle)) { SafeNativeMethods.CloseHandle(fileHandle); SafeNativeMethods.UnregisterDeviceNotification(deviceHandle); } }
private void UnregisterDeviceNotification(IntPtr deviceHandle, IntPtr fileHandle) { if (DeviceHandles.ContainsKey(deviceHandle)) { CloseHandle(fileHandle); UnregisterDeviceNotification(deviceHandle); } }
private void ProcessMessage(Message message) { if (message.Msg == WM_DEVICECHANGE) { switch (message.WParam.ToInt32()) { case DBT_DEVICEARRIVAL: if (Marshal.ReadInt32(message.LParam, 4) == DBT_DEVTYP_VOLUME) { DEV_BROADCAST_VOLUME volume = Marshal.PtrToStructure <DEV_BROADCAST_VOLUME>(message.LParam); string deviceName = DeviceMaskToDeviceName(volume.DBVC_UnitMask); DeviceArrived?.Invoke(this, new DeviceNotificationEventArgs(deviceName)); RegisterDeviceNotification(deviceName); } break; case DBT_DEVICEQUERYREMOVE: if (Marshal.ReadInt32(message.LParam, 4) == DBT_DEVTYP_HANDLE) { DEV_BROADCAST_HANDLE data = Marshal.PtrToStructure <DEV_BROADCAST_HANDLE>(message.LParam); if (DeviceHandles.ContainsKey(data.DBCH_HDevNotify)) { DeviceQueryRemove?.Invoke(this, new DeviceNotificationEventArgs(DeviceHandles[data.DBCH_HDevNotify])); } UnregisterDeviceNotification(data.DBCH_HDevNotify, data.DBCH_Handle); } break; case DBT_DEVICEREMOVECOMPLETE: if (Marshal.ReadInt32(message.LParam, 4) == DBT_DEVTYP_VOLUME) { DEV_BROADCAST_VOLUME volume = Marshal.PtrToStructure <DEV_BROADCAST_VOLUME>(message.LParam); string deviceName = DeviceMaskToDeviceName(volume.DBVC_UnitMask); DeviceRemoveComplete?.Invoke(this, new DeviceNotificationEventArgs(deviceName)); } break; } } }