Title: List USB devices in C#
This program uses WMI (Windows Management Instrumentation) to query for USB devices. To use WMI, add a references to System.Management and add a using System.Management directive.
When it starts, this example uses the following code to list USB devices.
// Add a reference to System.Management.
using System.Management;
...
private void Form1_Load(object sender, EventArgs e)
{
ManagementObjectSearcher device_searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_USBHub");
foreach (ManagementObject usb_device in device_searcher.Get())
{
ListViewItem new_item = lvwDevices.Items.Add(
usb_device.Properties["DeviceID"].Value.ToString());
new_item.SubItems.Add(
usb_device.Properties["PNPDeviceID"].Value.ToString());
new_item.SubItems.Add(
usb_device.Properties["Description"].Value.ToString());
}
}
This code creates a ManagementObjectSearcher to execute the WMI query SELECT * FROM Win32_USBHub. It then loops through the results displaying each USB device's plug and play ID and description.
For more information on the Win32_PnPEntity class, see its Microsoft web page.
Unfortunately I haven't figured out how to tell if a device is present and available for use. If you figure it out, post a comment below.
Download the example to experiment with it and to see additional details.
|