Detect And Event All USB Changes and Filter Devices
- Using
System.Management
Nuget package - All data get from WMI in system management
- Using Concurrent Collections (System.Collections.Concurrent) :
ConcurrentBag
,ConcurrentDictionary
- Using
setupapi.dll
for finding device parent and childs. so you cant use this library remotely such as WMI instructions. - .Net Core 8.0
- Windows Desktop
- List of USB Devices in pc
- List all of USB device childs
- Supported interfaces:
- Disk Drive
- Disk Partition
- Logical Disk
- Serial Port
- Serial Port Configuration
- Network Adapter
- Network Adapter Configuration
- Event Types:
- Connected
- Disconnected
- Modified
-
Create new instance of class
USBDevices
public USBDevices USBDevicesCollection { get; set; }
USBDevicesCollection = new();
-
By default Connected, Disconnected and Modified events are enabled if you want you can disable each of them by:
USBDevicesCollection.DisableConnectedEvents(); USBDevicesCollection.DisableDisconnectedEvents(); USBDevicesCollection.DisableModifiedEvents();
or you can enable them by:
USBDevicesCollection.EnableConnectedEvents(); USBDevicesCollection.EnableDisconnectedEvents(); USBDevicesCollection.EnableModifiedEvents();
-
You can set filter list to monitor usb devices. In this case you should enable the filter status by:
USBDevicesCollection.EnableFilterDevice();
you can diable filter status by:
USBDevicesCollection.DisableFilterDevice();
after enabling, add VID and PID to filter list. You can fillter both of VID & PID or only VID or PID. Such as
AddDeviceToFilter("xxxx", "yyyy")
orAddDeviceToFilter("xxxx", string.Empty)
orAddDeviceToFilter(string.Empty, "yyyy")
USBDevicesCollection.AddDeviceToFilter("xxxx", "yyyy");
you can remove from list of filtered devices by
RemoveDeviceFromFilter(vid, pid)
:USBDevicesCollection.RemoveDeviceFromFilter("xxxx", "yyyy");
-
Add Events :
USBDevicesCollection.InitialCollectionsComplete += USBDevicesCollections_InitialCollectionsComplete; USBDevicesCollection.CollectionChanged += USBDevicesCollection_CollectionChanged; USBDevicesCollection.DeviceChanged += USBDevicesCollections_DeviceChanged;
-
After initial
USBDevices
class you should start the monitiring byStart()
:USBDevicesCollection.Start();
-
USBDevices
class inherited fromConcurrent Dictionary
. You can access devices list byUSBDevicesCollection.Values
.
For more information study the codes or contact with me.