如何检查一个给定的USB设备是否已插入? [英] How do I check whether a given USB device is plugged in?

查看:169
本文介绍了如何检查一个给定的USB设备是否已插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的WinForms应用程序支持使用制造商提供的SDK定制的控制器,但没有支持,检测设备是否是present与否。如何检查一个给定的USB设备是否已插入?

Our winforms application supports a custom controller using the manufacturer's SDK, but there's no support to detect whether a device is present or not. How do I check whether a given USB device is plugged in?

推荐答案

下面的类是用来监控设备,您可以使用它来检测USB设备。

The following class is used to monitor devices, you could use this to detect a USB device.

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
    }
}

修改

从<一个提取href="http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/09912cee-4d2d-4efd-82a0-da20024b868b">http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/09912cee-4d2d-4efd-82a0-da20024b868b

这篇关于如何检查一个给定的USB设备是否已插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆