如何检测何时使用C#插入可移动磁盘?

我只关心Windows,所以不需要关于单声道兼容性或类似的东西。

我还应该补充说,我正在编写的应用程序是WPF,如果可能,我宁愿避免对System.Windows.Forms进行依赖。

给这个一个镜头…

 using System; using System.Collections.Generic; using System.Text; using System.Management; namespace WMITestConsolApplication { class Program { static void Main(string[] args) { AddInsertUSBHandler(); AddRemoveUSBHandler(); while (true) { } } static ManagementEventWatcher w = null; static void AddRemoveUSBHandler() { WqlEventQuery q; ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; try { q = new WqlEventQuery(); q.EventClassName = "__InstanceDeletionEvent"; q.WithinInterval = new TimeSpan(0, 0, 3); q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"; w = new ManagementEventWatcher(scope, q); w.EventArrived += USBRemoved; w.Start(); } catch (Exception e) { Console.WriteLine(e.Message); if (w != null) { w.Stop(); } } } static void AddInsertUSBHandler() { WqlEventQuery q; ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; try { q = new WqlEventQuery(); q.EventClassName = "__InstanceCreationEvent"; q.WithinInterval = new TimeSpan(0, 0, 3); q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"; w = new ManagementEventWatcher(scope, q); w.EventArrived += USBInserted; w.Start(); } catch (Exception e) { Console.WriteLine(e.Message); if (w != null) { w.Stop(); } } } static void USBInserted(object sender, EventArgs e) { Console.WriteLine("A USB device inserted"); } static void USBRemoved(object sender, EventArgs e) { Console.WriteLine("A USB device removed"); } } } 

与使用WMI轮询相比,执行此操作的方法要简单得多 – 只需捕获WM_DEVICECHANGE即可:

http://msdn.microsoft.com/en-us/library/aa363215.aspx

最简单的方法是创建一个自动播放处理程序:

http://www.codeproject.com/KB/system/AutoplayDemo.aspx

自动播放版本2是Windows XP中的一项功能,它将扫描可移动媒体的前四个级别,当它到达时,查找媒体内容类型(音乐,图形或视频)。 应用程序的注册是在内容类型的基础上完成的。 当可移动媒体到达时,Windows XP通过评估内容并将其与注册的处理程序进行比较来确定要执行的操作。

详细的MSDN文章也是可用的。