wpf/winform通过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");
        }

时间: 2024-10-01 01:31:05

wpf/winform通过WMI实现USB设备拔插检视的相关文章

Delphi调用WMI读取USB设备的PID和VID

WMI(WindowsManagement Instrumentation ) 非常强大,它可以以数据库的形式查询你的电脑的软件和硬件,在它的数据库里面,时刻保存着最新的软件信息和硬件信息,因此你可以用WMI来检测CUP 主频.温度,读取WINDOWS的进程......... 本文就介绍如何使用WMI读取USB设备的PID和VID码 1. Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 2. 3

usb-使用WMI获取 USB设备接口描述

问题描述 使用WMI获取 USB设备接口描述 我已经通过这篇文章C#:基于WMI查询USB设备 了解到使用通 SELECT * FROM Win32_PnPEntity WHERE DeviceID=" + Dependent 可以获取usb设备的deviceDescription 要查询usb的interfaceDescription 该用什么查询语句呢

USB设备驱动概述

USB设备驱动 ·  17.1 USB总线协议 ·  17.1.1 USB设备简介 ·  17.1.2 USB连接拓扑结构 ·  17.1.3 USB通信的流程 ·  17.1.4 USB四种传输模式 ·  17.2.1 观察USB设备的工具 ·  17.2.2 USB设备请求 ·  17.2.3 设备描述符 ·  17.2.4 配置描述符 ·  17.2.5 接口描述符 ·  17.2.6 端点描述符 ·  17.3.1 功能驱动与物理总线驱动 ·  17.3.2 构造USB请求包 ·  17

USB设备无法使用故障的排除

当你想用闪存或移动硬盘来和电脑交换数据时,但插上USB口时你却发现系统居然无法识别出USB设备,这是什么原因造成的呢?其实这样的现象我们时常见到,接下来介绍一下简单的处理方法. 一.在排除USB存储设备本身故障后,出现无法识别现象的原因一般是由以下几个方面所造成的: 一是USB接口电压不足.这种故障通常存在于移动硬盘身上,当把移动硬盘接在前置USB口上时就有可能发生系统无法识别出设备的故障,原因是移动硬盘功率比较大要求电压相对比较严格,前置的USB接口是通过线缆连接到机箱上的,在传输时便会消耗大

电脑无法识别usb设备怎么办

现在我们应用USB设备越来越多,而出现的问题也没少,软件硬件方面的问题也随着而来,那我们来分析下USB设备和故障解决. 1.前置USB线接错.当主板上的USB线和机箱上的前置USB 接口对应相接时把正负接反就会发生这类故障,这也是相当危险的,因为正负接反很可能会使得USB设备烧毁.所以尽量采用机箱后置的USB接口,也少用延长线.也可能是断口有问题,换个USB端口看下. 2.USB接口电压不足.当把移动硬盘接在前置USB口上时就有可能发生系统无法识别出设备的故障.原因是移动硬盘功率比较大要求电压相

Win8安装USB3.0 及USB设备的技巧

USB(通用串行总线)设备是最容易连接到电脑的设备之一. 你可以连接各种各样的设备,如键盘.打印机和外部驱动器.提醒 有些设备可能使用了 USB 3.0,这种连接类型的运行速度最多可比 USB 2.0 快 10 倍,因为它采用了一项名为 SuperSpeed 的新技术. 你可以通过下列符号之一来识别能够连接你的 USB 设备的电缆和端口. USB 2.0 符号 USB 3.0 符号 如果你安装的是 USB 3.0 设备,则可能有一根用于该设备的蓝色电缆. 你可能还会在电缆一端的连接器中以及电脑或

Win8无法识别新添加的USB设备

故障现象: Win8使用无线设备(无线鼠标,无线键盘,其它无线设备等)时,插上设备后无法正常识别,设备管理器中出现Unknown Device,无法识别的USB设备,驱动也无法正常安装. 原因分析: 该问题通常是设备故障.USB接口或者系统Plug and Play服务被关闭. 解决方案: 请打开控制面板--管理工具--服务--只需要开启 Plug and Play服务(使计算机在极少或没有用户输入的情况下能识别并适应硬件的更改.终止或禁用此服务会造成系统不稳定.),如果默认是开启的,请禁止,再

XP系统无法卸载USB设备怎么办?

XP系统无法卸载USB设备怎么办?   方案一: 1.完成U盘数据的操作后,关闭相应的程序.返回到"我的电脑"窗口中,打开一个驱动器进行文件夹操作(除了移动U盘外). 2.然后单击任务栏中的U盘图标,这时就会弹出安全删除U盘的对话框,单击"确定"按钮后即可将U盘从电脑上拔下来. 如果在该情况下还是无法卸载U盘等设备,那么你需要怀疑: a.检查是否还有程序占用了U盘的资源.比如音乐播放器.媒体文件以及部分装在U盘中的软件等.你可以使用Unlocker等软件解除这些资源

无法识别usb设备怎么办

usb设备越来越普遍,几乎所有的设备都有usb化的趋势,如打印机.摄像头.mp3.mp4.阅读机,但很多时候,我们使用usb设备却不是那么的顺利.经常出现"无法识别的usb设备"的提示,那么为什么会出现此提示,如何解决呢 步骤/方法 前置USB线接错.当主板上的USB线和机箱上的前置USB 接口对应相接时把正负接反就会发生这类故障,这也是相当危险的,因为正负接反很可能会使得USB设备烧毁.所以尽量采用机箱后置的USB接口,也少用延长线.也可能是断口有问题,换个USB端口看下. USB接