C#:基于WMI监视USB插拔

120 篇文章 3 订阅

作者:Splash

转自:http://blog.csdn.net/jhqin/article/details/6698411


参考资料:

USB Port Insert / Remove detection using WMI

USB Port Insert / Remove detection using WMI (Source Code)

下载:

USBWatcher.zip

实现类代码:

USBWatcher.cs

[csharp] view plain copy
  1. /* ---------------------------------------------------------- 
  2. 文件名称:WMIUsbWatcher.cs 
  3.  
  4. 作者:秦建辉 
  5.  
  6. MSN:splashcn@msn.com 
  7. QQ:36748897 
  8.  
  9. 博客:http://blog.csdn.net/jhqin 
  10.  
  11. 开发环境: 
  12.     Visual Studio V2010 
  13.     .NET Framework 4 Client Profile 
  14.  
  15. 版本历史: 
  16.     V1.1    2011年08月19日 
  17.             增加对插拔USB设备的定位 
  18.   
  19.     V1.0    2011年08月18日 
  20.             基于WMI实现对插拔USB设备的监视 
  21. ------------------------------------------------------------ */  
  22. using System;  
  23. using System.Management;  
  24.   
  25. namespace Splash.IO.PORTS  
  26. {  
  27.     /// <summary>  
  28.     /// USB控制设备类型  
  29.     /// </summary>  
  30.     public struct USBControllerDevice  
  31.     {  
  32.         /// <summary>  
  33.         /// USB控制器设备ID  
  34.         /// </summary>  
  35.         public String Antecedent;  
  36.   
  37.         /// <summary>  
  38.         /// USB即插即用设备ID  
  39.         /// </summary>  
  40.         public String Dependent;  
  41.     }  
  42.   
  43.     /// <summary>  
  44.     /// 监视USB插拔  
  45.     /// </summary>  
  46.     public partial class USB  
  47.     {          
  48.         /// <summary>  
  49.         /// USB插入事件监视  
  50.         /// </summary>  
  51.         private ManagementEventWatcher insertWatcher = null;  
  52.   
  53.         /// <summary>  
  54.         /// USB拔出事件监视  
  55.         /// </summary>  
  56.         private ManagementEventWatcher removeWatcher = null;  
  57.   
  58.         /// <summary>  
  59.         /// 添加USB事件监视器  
  60.         /// </summary>  
  61.         /// <param name="usbInsertHandler">USB插入事件处理器</param>  
  62.         /// <param name="usbRemoveHandler">USB拔出事件处理器</param>  
  63.         /// <param name="withinInterval">发送通知允许的滞后时间</param>  
  64.         public Boolean AddUSBEventWatcher(EventArrivedEventHandler usbInsertHandler, EventArrivedEventHandler usbRemoveHandler, TimeSpan withinInterval)  
  65.         {  
  66.             try  
  67.             {  
  68.                 ManagementScope Scope = new ManagementScope("root\\CIMV2");  
  69.                 Scope.Options.EnablePrivileges = true;  
  70.   
  71.                 // USB插入监视  
  72.                 if (usbInsertHandler != null)  
  73.                 {     
  74.                     WqlEventQuery InsertQuery = new WqlEventQuery("__InstanceCreationEvent",  
  75.                         withinInterval,  
  76.                         "TargetInstance isa 'Win32_USBControllerDevice'");  
  77.   
  78.                     insertWatcher = new ManagementEventWatcher(Scope, InsertQuery);  
  79.                     insertWatcher.EventArrived += usbInsertHandler;  
  80.                     insertWatcher.Start();  
  81.                 }  
  82.   
  83.                 // USB拔出监视  
  84.                 if (usbRemoveHandler != null)  
  85.                 {     
  86.                     WqlEventQuery RemoveQuery = new WqlEventQuery("__InstanceDeletionEvent",  
  87.                         withinInterval,  
  88.                         "TargetInstance isa 'Win32_USBControllerDevice'");  
  89.   
  90.                     removeWatcher = new ManagementEventWatcher(Scope, RemoveQuery);  
  91.                     removeWatcher.EventArrived += usbRemoveHandler;  
  92.                     removeWatcher.Start();  
  93.                 }  
  94.   
  95.                 return true;  
  96.             }  
  97.   
  98.             catch (Exception)  
  99.             {  
  100.                 RemoveUSBEventWatcher();  
  101.                 return false;  
  102.             }  
  103.         }  
  104.   
  105.         /// <summary>  
  106.         /// 移去USB事件监视器  
  107.         /// </summary>  
  108.         public void RemoveUSBEventWatcher()  
  109.         {  
  110.             if (insertWatcher != null)  
  111.             {  
  112.                 insertWatcher.Stop();  
  113.                 insertWatcher = null;  
  114.             }  
  115.   
  116.             if (removeWatcher != null)  
  117.             {  
  118.                 removeWatcher.Stop();  
  119.                 removeWatcher = null;  
  120.             }  
  121.         }          
  122.   
  123.         /// <summary>  
  124.         /// 定位发生插拔的USB设备  
  125.         /// </summary>  
  126.         /// <param name="e">USB插拔事件参数</param>  
  127.         /// <returns>发生插拔现象的USB控制设备ID</returns>  
  128.         public static USBControllerDevice[] WhoUSBControllerDevice(EventArrivedEventArgs e)  
  129.         {  
  130.             ManagementBaseObject mbo = e.NewEvent["TargetInstance"as ManagementBaseObject;  
  131.             if (mbo != null && mbo.ClassPath.ClassName == "Win32_USBControllerDevice")  
  132.             {  
  133.                 String Antecedent = (mbo["Antecedent"as String).Replace("\"", String.Empty).Split(new Char[] { '=' })[1];  
  134.                 String Dependent = (mbo["Dependent"as String).Replace("\"", String.Empty).Split(new Char[] { '=' })[1];  
  135.                 return new USBControllerDevice[1] { new USBControllerDevice { Antecedent = Antecedent, Dependent = Dependent } };  
  136.             }  
  137.   
  138.             return null;  
  139.         }  
  140.     }  
  141. }  

调用示例(线程安全):

[csharp] view plain copy
  1. using System;  
  2. using System.Windows.Forms;  
  3. using System.Management;  
  4. using Splash.IO.PORTS;  
  5.   
  6. namespace Splash  
  7. {  
  8.     public partial class Form1 : Form  
  9.     {  
  10.         USB ezUSB = new USB();  
  11.         
  12.         public Form1()  
  13.         {  
  14.             InitializeComponent();  
  15.         }  
  16.   
  17.         private void Form1_Load(object sender, EventArgs e)  
  18.         {  
  19.             ezUSB.AddUSBEventWatcher(USBEventHandler, USBEventHandler, new TimeSpan(0, 0, 3));  
  20.         }  
  21.   
  22.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
  23.         {  
  24.             ezUSB.RemoveUSBEventWatcher();  
  25.         }  
  26.   
  27.         private void USBEventHandler(Object sender, EventArrivedEventArgs e)  
  28.         {  
  29.             if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")  
  30.             {  
  31.                 this.SetText("USB插入时间:" + DateTime.Now + "\r\n");  
  32.             }  
  33.             else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")   
  34.             {  
  35.                 this.SetText("USB拔出时间:" + DateTime.Now + "\r\n");  
  36.             }  
  37.   
  38.             foreach (USBControllerDevice Device in USB.WhoUSBControllerDevice(e))  
  39.             {  
  40.                 this.SetText("\tAntecedent:" + Device.Antecedent + "\r\n");  
  41.                 this.SetText("\tDependent:" + Device.Dependent + "\r\n");  
  42.             }  
  43.         }  
  44.   
  45.         // 对 Windows 窗体控件进行线程安全调用  
  46.         private void SetText(String text)  
  47.         {  
  48.             if (this.textBox1.InvokeRequired)  
  49.             {  
  50.                 this.textBox1.BeginInvoke(new Action<String>((msg) =>    
  51.                 {  
  52.                     this.textBox1.AppendText(msg);    
  53.                 }), text);    
  54.             }  
  55.             else  
  56.             {  
  57.                 this.textBox1.AppendText(text);  
  58.             }  
  59.         }  
  60.     }  
  61. }  

演示界面:

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值