C# 如何检查给定的USB设备是否已插入?

C# 如何检查给定的USB设备是否已插入?,c#,.net,usb,C#,.net,Usb,我们的winforms应用程序支持使用制造商SDK的自定义控制器,但不支持检测设备是否存在。如何检查给定的USB设备是否已插入?以下类用于监视设备,您可以使用它来检测USB设备 using System; using System.Collections.Generic; using System.Text; using System.Management; namespace DeviceMonitor.Event { /// <summary>Media watcher

我们的winforms应用程序支持使用制造商SDK的自定义控制器,但不支持检测设备是否存在。如何检查给定的USB设备是否已插入?

以下类用于监视设备,您可以使用它来检测USB设备

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace DeviceMonitor.Event
{
    /// <summary>Media watcher delegate.</summary>
    /// <param name="sender"></param>
    /// <param name="driveStatus"></param>
    public delegate void MediaWatcherEventHandler(object sender, DeviceMonitor.Event.MediaEvent.DriveStatus driveStatus );

    /// <summary>Class to monitor devices.</summary>
    public class MediaEvent
    {
        #region Variables

        /*------------------------------------------------------------------------*/
        private string m_logicalDrive;
        private ManagementEventWatcher m_managementEventWatcher = null;
        /*------------------------------------------------------------------------*/
        #endregion

        #region Events
        /*------------------------------------------------------------------------*/
        public event MediaWatcherEventHandler MediaWatcher;
        /*------------------------------------------------------------------------*/
        #endregion


        #region Enums
        /*------------------------------------------------------------------------*/
        /// <summary>The drive types.</summary>
        public enum DriveType
        {
          Unknown = 0,
          NoRootDirectory = 1,
          RemoveableDisk  = 2,
          LocalDisk       = 3,
          NetworkDrive    = 4,
          CompactDisk     = 5,
          RamDisk         = 6
        }

        /// <summary>The drive status.</summary>
        public enum DriveStatus
        {
          Unknown  = -1,
          Ejected  = 0,
          Inserted = 1,
        }

       /*-----------------------------------------------------------------------*/
       #endregion


       #region Monitoring
       /*-----------------------------------------------------------------------*/
       /// <summary>Starts the monitoring of device.</summary>
       /// <param name="path"></param>
       /// <param name="mediaEvent"></param>
       public void Monitor( string path, MediaEvent mediaEvent ) 
       {
           if( null == mediaEvent ) 
           {
              throw new ArgumentException( "Media event cannot be null!" );
           }

           //In case same class was called make sure only one instance is running
           /////////////////////////////////////////////////////////////
           this.Exit();

           //Keep logica drive to check
           /////////////////////////////////////////////////////////////
           this.m_logicalDrive = this.GetLogicalDrive( path );

           WqlEventQuery wql;
           ManagementOperationObserver observer = new ManagementOperationObserver();

           //Bind to local machine
           /////////////////////////////////////////////////////////////
           ConnectionOptions opt = new ConnectionOptions();

           //Sets required privilege
           /////////////////////////////////////////////////////////////
           opt.EnablePrivileges = true;
           ManagementScope scope = new ManagementScope( "root\\CIMV2", opt );

           try 
           {
              wql = new WqlEventQuery();
              wql.EventClassName = "__InstanceModificationEvent";
              wql.WithinInterval = new TimeSpan( 0, 0, 1 );

              wql.Condition = String.Format( @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DeviceId = '{0}'", this.m_logicalDrive );
              this.m_managementEventWatcher = new ManagementEventWatcher( scope, wql );

              //Register async. event handler
              /////////////////////////////////////////////////////////////
              this.m_managementEventWatcher.EventArrived += new EventArrivedEventHandler( mediaEvent.MediaEventArrived );
              this.m_managementEventWatcher.Start();
           } 
           catch( Exception e ) 
           {
              this.Exit();
              throw new Exception( "Media Check: "  + e.Message );
           }
       }

       /// <summary>Stops the monitoring of device.</summary>
       public void Exit( ) 
       {
             //In case same class was called make sure only one instance is running
             /////////////////////////////////////////////////////////////
             if( null != this.m_managementEventWatcher ) 
             {
                  try 
                  {
                       this.m_managementEventWatcher.Stop();
                       this.m_managementEventWatcher = null;
                  } 
                  catch {}
             }
        }
        /*-----------------------------------------------------------------------*/
        #endregion


        #region Helpers
        /*-----------------------------------------------------------------------*/

        private DriveStatus m_driveStatus = DriveStatus.Unknown;

        /// <summary>Triggers the event when change on device occured.</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MediaEventArrived( object sender, EventArrivedEventArgs e ) 
        {

            // Get the Event object and display it
            PropertyData pd = e.NewEvent.Properties["TargetInstance"];
            DriveStatus driveStatus = this.m_driveStatus;

            if( pd != null ) 
            {
                ManagementBaseObject mbo = pd.Value as ManagementBaseObject;
                System.IO.DriveInfo info = new System.IO.DriveInfo( (string)mbo.Properties["DeviceID"].Value );
                driveStatus = info.IsReady ? DriveStatus.Inserted : DriveStatus.Ejected;
            }

            if( driveStatus != this.m_driveStatus )
            {
                this.m_driveStatus = driveStatus;
                if( null != MediaWatcher ) 
                {
                    MediaWatcher( sender, driveStatus );
                }
            }
        }


        /// <summary>Gets the logical drive of a given path.</summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string GetLogicalDrive( string path ) 
        {
            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo( path );
            string root = dirInfo.Root.FullName;
            string logicalDrive = root.Remove(root.IndexOf(System.IO.Path.DirectorySeparatorChar ) );
            return logicalDrive;
        }
        /*-----------------------------------------------------------------------*/
        #endregion
    }
}
使用系统;
使用System.Collections.Generic;
使用系统文本;
使用制度管理;
命名空间DeviceMonitor.Event
{
///媒体观察者代表。
/// 
/// 
公共委托无效MediaWatcherEventHandler(对象发送方,DeviceMonitor.Event.MediaEvent.DriveStatus DriveStatus);
///类来监视设备。
公共类媒体活动
{
#区域变量
/*------------------------------------------------------------------------*/
私有字符串m_logicalDrive;
私有ManagementEventWatcher m_ManagementEventWatcher=null;
/*------------------------------------------------------------------------*/
#端区
#地区活动
/*------------------------------------------------------------------------*/
公共事件媒体观察者事件观察者;
/*------------------------------------------------------------------------*/
#端区
#区域枚举
/*------------------------------------------------------------------------*/
///驱动器类型。
公共枚举驱动类型
{
未知=0,
NoRootDirectory=1,
RemoveableDisk=2,
LocalDisk=3,
NetworkDrive=4,
压缩磁盘=5,
RamDisk=6
}
///驱动器状态。
公共枚举驱动器状态
{
未知=-1,
弹出=0,
插入=1,
}
/*-----------------------------------------------------------------------*/
#端区
#区域监测
/*-----------------------------------------------------------------------*/
///启动设备的监视。
/// 
/// 
公共无效监视器(字符串路径,MediaEvent MediaEvent)
{
if(null==mediaEvent)
{
抛出新ArgumentException(“媒体事件不能为null!”);
}
//如果调用了同一个类,请确保只有一个实例正在运行
/////////////////////////////////////////////////////////////
这是Exit();
//让logica驱动器进行检查
/////////////////////////////////////////////////////////////
this.m_logicalDrive=this.GetLogicalDrive(路径);
wqleventquerywql;
ManagementOperationObserver observer=新的ManagementOperationObserver();
//绑定到本地计算机
/////////////////////////////////////////////////////////////
ConnectionOptions opt=新的ConnectionOptions();
//设置所需的权限
/////////////////////////////////////////////////////////////
opt.EnablePrivileges=true;
ManagementScope范围=新的管理范围(“根\\CIMV2”,opt);
尝试
{
wql=新的WqlEventQuery();
wql.EventClassName=“\uu InstanceModificationEvent”;
wql.WithinInterval=新的时间跨度(0,0,1);
wql.Condition=String.Format(@“TargetInstance ISA'Win32_LogicalDisk'和TargetInstance.DeviceId='{0}',this.m_logicalDrive);
this.m_managementEventWatcher=新的managementEventWatcher(范围,wql);
//注册异步事件处理程序
/////////////////////////////////////////////////////////////
this.m_managementEventWatcher.EventArrived+=新的EventArriveDevenHandler(mediaEvent.MediaEventArrived);
此.m_managementEventWatcher.Start();
} 
捕获(例外e)
{
这是Exit();
抛出新异常(“媒体检查:+e.消息”);
}
}
///停止对设备的监视。
公共无效出口()
{
//如果调用了同一个类,请确保只有一个实例正在运行
/////////////////////////////////////////////////////////////
if(null!=此.m_managementEventWatcher)
{
尝试
{
此.m_managementEventWatcher.Stop();
this.m_managementEventWatcher=null;
} 
捕获{}
}
}
/*-----------------------------------------------------------------------*/
#端区
#地区助手
/*-----------------------------------------------------------------------*/
private DriveStatus m_DriveStatus=DriveStatus.未知;
///在设备发生更改时触发事件。
/// 
/// 
私有void MediaEventArrived(对象发送方,EventArrivedEventArgs e)
{
//获取事件对象并显示它
PropertyData pd=e.NewEvent.Properties[“TargetInstance”];
DriveStatus DriveStatus=此.m_DriveStatus;
如果(pd!=null)
{
ManagementBaseObject mbo=pd.Value作为ManagementBaseObject;
System.IO.DriveInfo info=new System.IO.DriveInfo((字符串)mbo.Properties[“DeviceID”].Value);
driveStatus=info.IsReady?driveStatus.Inserted:driveStatus.Ejected;
}
if(driveStatus!=此.m_driveStatus)
{
this.m_driveStatus=driveStatus;
if(null!=MediaWatcher)
{
MediaWatcher(发送方、驱动器状态);
}
}
}
///获取给定pat的逻辑驱动器