现在位置首页 / 项目实战 /正文

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

作者: IT小兵 | 2016年11月4日| 热度:℃ | 评论: |参与:

在上一篇[WPF实现Winform的窗口消息WndProc]中,介绍了使用WndProc消息,实现对usb设备的检视,今天分享一篇,通过WMI的事件方法,实现对USB设备的监控。

本文用到的开源类,百度云下载:链接: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
{
    /// <summary>  
    /// USB控制设备类型  
    /// </summary>  
    public struct USBControllerDevice
    {
        /// <summary>  
        /// USB控制器设备ID  
        /// </summary>  
        public String Antecedent;
        /// <summary>  
        /// USB即插即用设备ID  
        /// </summary>  
        public String Dependent;
    }
    /// <summary>  
    /// 监视USB插拔  
    /// </summary>  
    public partial class USB
    {
        /// <summary>  
        /// USB插入事件监视  
        /// </summary>  
        private ManagementEventWatcher insertWatcher = null;
        /// <summary>  
        /// USB拔出事件监视  
        /// </summary>  
        private ManagementEventWatcher removeWatcher = null;
        /// <summary>  
        /// 添加USB事件监视器  
        /// </summary>  
        /// <param name="usbInsertHandler">USB插入事件处理器</param>  
        /// <param name="usbRemoveHandler">USB拔出事件处理器</param>  
        /// <param name="withinInterval">发送通知允许的滞后时间</param>  
        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;
            }
        }
        /// <summary>  
        /// 移去USB事件监视器  
        /// </summary>  
        public void RemoveUSBEventWatcher()
        {
            if (insertWatcher != null)
            {
                insertWatcher.Stop();
                insertWatcher = null;
            }
            if (removeWatcher != null)
            {
                removeWatcher.Stop();
                removeWatcher = null;
            }
        }
        /// <summary>  
        /// 定位发生插拔的USB设备  
        /// </summary>  
        /// <param name="e">USB插拔事件参数</param>  
        /// <returns>发生插拔现象的USB控制设备ID</returns>  
        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<PnPEntityInfo> 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");
        }


点击阅读本文所属分类的更多文章: 项目实战 。和高手一起交流:346717337
友荐云推荐

未注明转发、原文均为本站原创。分享本文请注明 原文链接

给您更多信息和帮助

在这里您可以找到更多:

技术交流群:346717337 Jquery插件交流

投稿:suchso@vip.qq.com

承接:企业网站门户/微网站/微商城/CMS系统/微信公众号运营/业务咨询

echarts教程系列
本月最热文章

微信扫一扫,徜徉悠嘻网,您的休闲乐园

微信公众号:快乐每一天

随机文章
标签

技术交流群:346717337

投稿:suchso@vip.qq.com

专业专注:企业网站门户/微网站/微商城/CMS系统/微信公众号运营/付费问题咨询