使用C#进行便携设备检测

时间:2014-06-18 06:48:08

标签: c# winforms wpd

检测便携式设备时遇到问题,特别是三星手机或iphone。 我需要开发一个程序,一旦检测到便携式插件就会启动并在插入后停止。

我一直在尝试使用此代码,但仅适用于带存储的USB设备,而不适用于便携式设备。

private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{
    ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
    foreach (var property in instance.Properties)
    {
        Console.WriteLine(property.Name + " = " + property.Value);
    }
}

void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
    ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
    foreach (var property in instance.Properties)
    {
        Console.WriteLine(property.Name + " = " + property.Value);
    }
}            

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");

    ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
    insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
    insertWatcher.Start();

    WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
    ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
    removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
    removeWatcher.Start();

    // Do something while waiting for events
    System.Threading.Thread.Sleep(20000000);
}

请帮忙。感谢

1 个答案:

答案 0 :(得分:1)

你试过这个:

System.IO.DriveInfo [] drives = System.IO.DriveInfo.GetDrives ();
foreach (System.IO.DriveInfo drive in drives)
{
  if (drive.DriveType == DriveType.Removable)
  {
    Console.WriteLine ("Found removable drive {0}", drive.Name);
  }
}

有关DriveInfo

的更多信息