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后,程序会捕获到两次事件,在此抛砖引玉,望高手不吝赐教!

  • 相关阅读:
    [leetcode]259. 3Sum Smaller 三数之和小于目标值
    题型总结之K Sum
    [Leetcode]167. Two Sum II
    题型总结之Sliding Window
    [Leetcode]703. Kth Largest Element in a Stream 数据流中的第 K 大元素
    [Leetcode]307. Range Sum Query
    pycharm同一目录下无法import明明已经存在的.py文件
    python高级特性:迭代器与生成器
    self的含义,为什么类调用方法时需要传参数?
    git三:远程仓库GitHub
  • 原文地址:https://www.cnblogs.com/moonlight-zjb/p/3446903.html
Copyright © 2011-2022 走看看