我在Visual Studio中使用C#,我想检测是否插入了特定的USB设备。我希望我的程序的一部分可以让用户查看所有插入的设备,并选择他们的设备,这将保存'设备的唯一属性,以便在插入设备时,代码可以检查此设备是否已保存。
到目前为止,我有一个代码可以检测何时插入任何USB并显示一个消息框,而且我还有一段代码可以找到所有插入的USB设备并返回其属性。
我现在需要能够确定新插入设备的属性(而不是仅显示消息框),以便我可以检查属性。此外,我不确定USB设备的哪个属性最好使用唯一标识符。
感谢您的帮助。
检测插入记忆棒的代码:
Using System.Management;
public Form1()
{
InitializeComponent();
ManagementEventWatcher usbWatcher = new ManagementEventWatcher(queryString);
usbWatcher.EventArrived += new EventArrivedEventHandler(OnCreation);
usbWatcher.Start();
}
public static string queryString =
@"SELECT *
FROM __InstanceOperationEvent
WITHIN 1
WHERE
TargetInstance ISA 'Win32_USBHub'";
private void OnCreation(object sender, EventArrivedEventArgs e)
{
MessageBox.Show("Memory Stick detected.");
}
查找已连接设备的代码:
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub");
foreach (var device in searcher.Get())
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description"),
(string)device.GetPropertyValue("Name")
));
}
return devices;
}
class USBDeviceInfo
{
public USBDeviceInfo(string deviceID, string pnpDeviceID, string description, string name)
{
this.DeviceID = deviceID;
this.PnpDeviceID = pnpDeviceID;
this.Description = description;
this.Name = name;
}
public string DeviceID { get; private set; }
public string PnpDeviceID { get; private set; }
public string Description { get; private set; }
public string Name { get; private set; }
}
public void usbSearch()
{
var usbDevices = GetUSBDevices();
foreach (var usbDevice in usbDevices)
{
MessageBox.Show(usbDevice.DeviceID + " " + usbDevice.PnpDeviceID + " " + usbDevice.Description);
}
}