作者:Splash
转自:http://blog.csdn.net/jhqin/article/details/6698411
参考资料:
下载:
实现类代码:
USBWatcher.cs
- /* ----------------------------------------------------------
- 文件名称:WMIUsbWatcher.cs
- 作者:秦建辉
- MSN:splashcn@msn.com
- QQ:36748897
- 博客:http://blog.csdn.net/jhqin
- 开发环境:
- Visual Studio V2010
- .NET Framework 4 Client Profile
- 版本历史:
- V1.1 2011年08月19日
- 增加对插拔USB设备的定位
- V1.0 2011年08月18日
- 基于WMI实现对插拔USB设备的监视
- ------------------------------------------------------------ */
- using System;
- using System.Management;
- namespace Splash.IO.PORTS
- {
- /// <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("\"", String.Empty).Split(new Char[] { '=' })[1];
- String Dependent = (mbo["Dependent"] as String).Replace("\"", String.Empty).Split(new Char[] { '=' })[1];
- return new USBControllerDevice[1] { new USBControllerDevice { Antecedent = Antecedent, Dependent = Dependent } };
- }
- return null;
- }
- }
- }
调用示例(线程安全):
- using System;
- using System.Windows.Forms;
- using System.Management;
- using Splash.IO.PORTS;
- namespace Splash
- {
- public partial class Form1 : Form
- {
- USB ezUSB = new USB();
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- ezUSB.AddUSBEventWatcher(USBEventHandler, USBEventHandler, new TimeSpan(0, 0, 3));
- }
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- ezUSB.RemoveUSBEventWatcher();
- }
- private void USBEventHandler(Object sender, EventArrivedEventArgs e)
- {
- if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
- {
- this.SetText("USB插入时间:" + DateTime.Now + "\r\n");
- }
- else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
- {
- this.SetText("USB拔出时间:" + DateTime.Now + "\r\n");
- }
- foreach (USBControllerDevice Device in USB.WhoUSBControllerDevice(e))
- {
- this.SetText("\tAntecedent:" + Device.Antecedent + "\r\n");
- this.SetText("\tDependent:" + Device.Dependent + "\r\n");
- }
- }
- // 对 Windows 窗体控件进行线程安全调用
- private void SetText(String text)
- {
- if (this.textBox1.InvokeRequired)
- {
- this.textBox1.BeginInvoke(new Action<String>((msg) =>
- {
- this.textBox1.AppendText(msg);
- }), text);
- }
- else
- {
- this.textBox1.AppendText(text);
- }
- }
- }
- }
演示界面: