一聚教程网:一个值得你收藏的教程网站

最新下载

wpf/winform通过WMI实现USB设备拔插检视

时间:2016-11-05 00:00:00 编辑:简简单单 来源:转载

文用到的开源类,百度云下载:链接:http://pan.baidu.com/s/1kVJfGsJ   密码:tkna

1、首先USB工具类DriveDetector.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
namespace StarsCloud.Comet.Common
{
    ///

 
    /// USB控制设备类型 
    ///
 
    public struct USBControllerDevice
    {
        ///  
        /// USB控制器设备ID 
        ///
 
        public String Antecedent;
        ///  
        /// USB即插即用设备ID 
        ///
 
        public String Dependent;
    }
    ///  
    /// 监视USB插拔 
    ///
 
    public partial class USB
    {
        ///  
        /// USB插入事件监视 
        ///
 
        private ManagementEventWatcher insertWatcher = null;
        ///  
        /// USB拔出事件监视 
        ///
 
        private ManagementEventWatcher removeWatcher = null;
        ///  
        /// 添加USB事件监视器 
        ///
 
        /// USB插入事件处理器 
        /// USB拔出事件处理器 
        /// 发送通知允许的滞后时间 
        public Boolean AddUSBEventWatcher(EventArrivedEventHandler usbInsertHandler, EventArrivedEventHandler usbRemoveHandler, TimeSpan withinInterval)
        {
            try
            {
                ManagementScope Scope = new ManagementScope("root\\CIMV2");
                Scope.Options.EnablePrivileges = true;
                // USB插入监视 
                if (usbInsertHandler != null)
                {
                    WqlEventQuery InsertQuery = new WqlEventQuery("__InstanceCreationEvent",
                        withinInterval,
                        "TargetInstance isa 'Win32_USBControllerDevice'");
                    insertWatcher = new ManagementEventWatcher(Scope, InsertQuery);
                    insertWatcher.EventArrived += usbInsertHandler;
                    insertWatcher.Start();
                }
                // USB拔出监视 
                if (usbRemoveHandler != null)
                {
                    WqlEventQuery RemoveQuery = new WqlEventQuery("__InstanceDeletionEvent",
                        withinInterval,
                        "TargetInstance isa 'Win32_USBControllerDevice'");
                    removeWatcher = new ManagementEventWatcher(Scope, RemoveQuery);
                    removeWatcher.EventArrived += usbRemoveHandler;
                    removeWatcher.Start();
                }
                return true;
            }
            catch (Exception)
            {
                RemoveUSBEventWatcher();
                return false;
            }
        }
        ///  
        /// 移去USB事件监视器 
        ///
 
        public void RemoveUSBEventWatcher()
        {
            if (insertWatcher != null)
            {
                insertWatcher.Stop();
                insertWatcher = null;
            }
            if (removeWatcher != null)
            {
                removeWatcher.Stop();
                removeWatcher = null;
            }
        }
        ///  
        /// 定位发生插拔的USB设备 
        ///
 
        /// USB插拔事件参数 
        /// 发生插拔现象的USB控制设备ID 
        public static USBControllerDevice[] WhoUSBControllerDevice(EventArrivedEventArgs e)
        {
            ManagementBaseObject mbo = e.NewEvent["TargetInstance"] as ManagementBaseObject;
            if (mbo != null && mbo.ClassPath.ClassName == "Win32_USBControllerDevice")
            {
                String Antecedent = (mbo["Antecedent"] as String).Replace("\"","").Split(new Char[] { '=' })[1];
                String Dependent = (mbo["Dependent"] as String).Replace("\"", "").Split(new Char[] { '=' })[1];
                return new USBControllerDevice[1] { new USBControllerDevice { Antecedent = Antecedent, Dependent = Dependent } };
            }
            return null;
        }
    }
}

2、在wpf或者控件窗口cs中,调用:

Common.USB ezUSB = new Common.USB();
        
bool IsOpeningCamera = false;
DateTime Benginopen = DateTime.Now;

注意:因为usb拔插的时候,事件会触发3次,我这里用一个时间戳记录,在10秒范围内的usb拔插就不处理了。当然也有问题。

注册事件:

ezUSB.AddUSBEventWatcher(USBEventHandler, USBEventHandler, new TimeSpan(0, 0,3));

3、事件实现:

 private void USBEventHandler(Object sender, EventArrivedEventArgs e)
        {
            if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
            {
                foreach (USBControllerDevice Device in Common.USB.WhoUSBControllerDevice(e))
                {
                    int i = 0;
                    Match match = Regex.Match(Device.Dependent, "VID_[0-9|A-F]{4}&PID_[0-9|A-F]{4}");
                    if (match.Success)
                    {
                        HIDD_VIDPID Entity;
                        Entity.VendorID = Convert.ToUInt16(match.Value.Substring(4, 4), 16);    // 供应商标识                
                        Entity.ProductID = Convert.ToUInt16(match.Value.Substring(13, 4), 16);  // 产品编号
                        PnPEntityInfo[] model = Splash.IO.PORTS.USB.WhoPnPEntity(Device.Dependent);
                        if (model != null && model.Length > 0)
                        {//得到一个usb设备
                            foreach (PnPEntityInfo pn in model)
                            {
                                if (pn.Description.IndexOf(StaticResourceHandller.化学相机名称.值) >= 0 && pn.Name.Trim().IndexOf(StaticResourceHandller.化学相机描述.值) >= 0)
                                {
                                    //MessageBox.Show(pn.Description);
                                    if (IsOpeningCamera == false)
                                    {
                                        IsOpeningCamera = true;
                                        this.Dispatcher.Invoke(new Action(() => {
                                            if (Benginopen.AddSeconds(15) < DateTime.Now)
                                            {
                                                Benginopen = DateTime.Now;
                                                cameraOpen(true);
                                            }
                                            IsOpeningCamera = false;
                                        }));
                                    }
                                }
                                else if (pn.Description.IndexOf(StaticResourceHandller.化学Com匹配描述.值) >= 0)
                                {
                                    //MessageBox.Show(pn.Description);
                                    if (IsOpeningCamera == false)
                                    {
                                        IsOpeningCamera = true;
                                         
                                            if (Benginopen.AddSeconds(15) < DateTime.Now)
                                            {
                                                Benginopen = DateTime.Now;
                                            //取出com口
                                            string comname = pn.Name.Replace(StaticResourceHandller.Com匹配描述.值, "").Replace("(","").Replace(")", "").Trim();
                                            List allexitescom = model.Where(a => a.Name.Replace(StaticResourceHandller.干化学Com匹配描述.值, "").Replace("(", "").Replace(")", "").Trim()==
                                            StaticResourceHandller.Com口.值
                                            ).ToList();//看一下有没有相同的端口配置。有的话,说明配置了,
                                                if (StaticResourceHandller.镜Com口.值 != comname )
                                                {//高倍镜没有占用
                                                    StaticResourceHandller.配置化学com口(comname);
                                                }
                                            }
                                            IsOpeningCamera = false;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
            {
                //    this.SetText("USB拔出时间:" + DateTime.Now + "\r\n");
            }
            // this.SetText("USB插入时间:" + DateTime.Now + "\r\n");
            //     this.SetText("\tAntecedent:" + Device.Antecedent + "\r\n");
            //    this.SetText("\tDependent:" + Device.Dependent + "\r\n");
        }

网站留言

热门栏目