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

  • 相关阅读:
    Django对静态文件的处理——部署阶段
    使用Django来处理对于静态文件的请求
    Django1.7如何配置静态资源访问
    Spring WebSocket中403错误解决
    FastJSON JSONObject 字段排序 Feature.OrderedField
    国际化(i18n) 各国语言缩写
    【转】java.io.Closeable接口
    【转】spring bean 卸载
    This content should also be served over HTTPS
    Failed to close the ServletOutputStream connection cleanly, Broken pipe
  • 原文地址:https://www.cnblogs.com/moonlight-zjb/p/3446903.html
Copyright © 2011-2022 走看看