How do I detect insertion of USB devices category wise in C# winform?

梦想与她 提交于 2021-02-07 04:00:47

问题


USB thumb drives
USB harddisks
USB DVD writer
USB Bluetooth devices
USB headsets
usb mouse
USB keyboard
USB webcams / cameras

Just want to detect any sort of usb device using event handler... Would appreciate any help...

WqlEventQuery q_creation = new WqlEventQuery();
 private void Form2_Load(object sender, EventArgs e)
        {



            q_creation.EventClassName = "__InstanceCreationEvent";
            q_creation.WithinInterval = new TimeSpan(0, 0, 2);    //How often do you want to check it? 2Sec.
            q_creation.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";
            var mwe_creation = new ManagementEventWatcher(q_creation);
            mwe_creation.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);
            mwe_creation.Start(); // Start listen for events
}                                                                                    
 /// <summary>
        /// Callback event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void USBEventArrived_Creation(object sender, EventArrivedEventArgs e)
        {
            MessageBox.Show("Device Connected");
        }

This is the code what i had tried.


回答1:


I am pasting my entire class for you, use as is (hookup the events right at the bottom for detecting or removal of USB) :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BlueMercs.Core.Services.WMI
{

  public class EventUsbMonitorEvent : EventArgs
  {
    public string Model { get; set; }
    public string Drive { get; set; }
  }

  public class UsbMonitor
  {
    private const string _queryForEvents = @"SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_DiskDrive'";
    private string _queryDiskPartitionDevice = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=\"{0}\"} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
    private string _queryDiskLogicalPartition = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=\"{0}\"} WHERE AssocClass = Win32_LogicalDiskToPartition";



    private readonly ManagementEventWatcher _watcher;
    private Thread _thread;

    public UsbMonitor()
    {
      _watcher = new ManagementEventWatcher();
      var query = new WqlEventQuery(_queryForEvents);
      _watcher.EventArrived += Watcher_EventArrived;
      _watcher.Query = query;
    }

    public void Start()
    {
      _watcher.Start();
      _thread = new Thread(Listen);
      _thread.Start();
    }

    public void Stop()
    {
      try { _thread.Abort(); } catch { } //suppress thread abort exception
      _watcher.Stop();
    }

    private void Listen()
    {
      _watcher.WaitForNextEvent();
      Listen();
    }

    private string GetDriveLetterFromDisk(string name)
    {
      name = name.Replace(@"\", @"\\");
      var driveLetter = string.Empty;
      var qryPartition = new ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=\"" + name + "\"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"); //string.Format(_queryDiskPartitionDevice, name));
      var partition = new ManagementObjectSearcher(qryPartition);

      foreach (var result in partition.Get())
      {
        //var qryLogicalDisk = new ObjectQuery(string.Format(_queryDiskLogicalPartition, result["DeviceID"]));
        var logicalDisk = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=\"" + result["DeviceID"] + "\"} WHERE AssocClass = Win32_LogicalDiskToPartition"); //qryLogicalDisk);
        driveLetter = logicalDisk.Get().Cast<ManagementBaseObject>().Aggregate(driveLetter, (current, x) => current + (x["Name"] + ","));
      }

      return driveLetter.Trim(',');
    }

    private void Watcher_EventArrived(object sender, EventArrivedEventArgs e)
    {
      ManagementBaseObject targetInstance;

      switch (e.NewEvent.ClassPath.ClassName)
      {
        case "__InstanceCreationEvent":
          targetInstance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
          if (targetInstance["InterfaceType"].ToString() == "USB")
          {
            var driveName = targetInstance["Caption"].ToString();
            var driveLetter = GetDriveLetterFromDisk(targetInstance["Name"].ToString());
            if (OnExternalUsbDetected != null)
              OnExternalUsbDetected(this, new EventUsbMonitorEvent { Model = driveName, Drive = driveLetter });
          }
          break;

        case "__InstanceDeletionEvent":
          targetInstance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
          if (targetInstance["InterfaceType"].ToString() == "USB")
          {
            var driveName = targetInstance["Caption"].ToString();
            var driveLetter = GetDriveLetterFromDisk(targetInstance["Name"].ToString());
            if (OnExternalUsbRemoved != null)
              OnExternalUsbRemoved(this, new EventUsbMonitorEvent { Model = driveName, Drive = driveLetter });
          }
          break;
      }
    }

    public event EventHandler<EventUsbMonitorEvent> OnExternalUsbDetected;
    public event EventHandler<EventUsbMonitorEvent> OnExternalUsbRemoved;
  }
}


来源:https://stackoverflow.com/questions/32458339/how-do-i-detect-insertion-of-usb-devices-category-wise-in-c-sharp-winform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!