zoukankan      html  css  js  c++  java
  • USB Key插入和移除监控

    近期在做USB Key插入和移除监控,已经做到了插入和移除USB Key时,程序能够及时感应到。

    如下为源代码:

    private void Form1_Load(object sender, EventArgs e)
    {
    //创建查询条件,监控USB Key插入和拔出
    string condintion = "TargetInstance ISA 'Win32_USBControllerdevice'";
    var qCreate = new WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(1), condintion);
    var qDelete = new WqlEventQuery("__InstanceDeletionEvent", TimeSpan.FromSeconds(1), condintion);

    //创建事件查询的侦听器(ManagementEventWatcher) 
    var wCreate = new ManagementEventWatcher(qCreate);
    var wDelete = new ManagementEventWatcher(qDelete);

    //事件注册代码
    wCreate.EventArrived += (sender1, e1) =>
    {
    GetInfo(e1.NewEvent);
    string msg = "插入USB Key!"; //+ GetInfo(e1.NewEvent);
    this.Write(msg);
    };
    wDelete.EventArrived += (sender1, e1) =>
    {
    string msg = "拔出USB Key!"; //+ GetInfo(e1.NewEvent);
    this.Write(msg);
    };

    //异步开始侦听
    wCreate.Start();
    wDelete.Start();
    }

    用了招行网银USB key和客户提供的USB key测试,运行结果如下:

    2013/11/28 0:51:17 插入USB Key!
    2013/11/28 0:51:17 插入USB Key!
    2013/11/28 0:51:18 拔出USB Key!
    2013/11/28 0:51:18 拔出USB Key!
    2013/11/28 0:51:20 插入USB Key!
    2013/11/28 0:51:21 拔出USB Key!
    2013/11/28 0:51:23 插入USB Key!
    2013/11/28 0:51:23 插入USB Key!
    2013/11/28 0:51:24 拔出USB Key!
    2013/11/28 0:51:24 拔出USB Key! 
    2013/11/28 0:51:55 插入USB Key!
    2013/11/28 0:51:55 插入USB Key! 
    2013/11/28 0:51:56 拔出USB Key!
    2013/11/28 0:51:56 拔出USB Key!

    不解的是,为什么我插入或拔出了一次Key后,程序会捕获到两次事件,在此抛砖引玉,望高手不吝赐教!

  • 相关阅读:
    CAF(C++ Actor Framework)介绍
    Android C++打印函数调用栈
    80%应聘者都不及格的JS面试题
    二叉树的最近公共祖先--递归解法
    mysql的InnoDB引擎的行记录格式ROW_FORMAT
    Docker安装mysql 集群(pxc方式)及负载均衡实践
    主机ping不通虚拟机,虚拟机可以ping通主机解决方式
    springboot源码解析
    springmvc源码解析
    寻找两个正序数组的中位数
  • 原文地址:https://www.cnblogs.com/moonlight-zjb/p/3446903.html
Copyright © 2011-2022 走看看