转自:原作者 由于工作中需要检测优盘是否存在,读取优盘中的文件,所有在此记录。
把优盘的信息读取封装到一个类:
using System; using System.IO; using System.Linq; using System.Windows.Forms; namespace TempControl.Classes { internal class FlashDisk { private const int WmDeviceChange = 0x219;//U盘插入后,OS的底层会自动检测到,然后向应用程序发送“硬件设备状态改变“的消息 private const int DbtDeviceArrival = 0x8000; //就是用来表示U盘可用的。一个设备或媒体已被插入一块,现在可用。 private const int DbtConfigChangeCanceled = 0x0019; //要求更改当前的配置(或取消停靠码头)已被取消。 private const int DbtConfigchanged = 0x0018; //当前的配置发生了变化,由于码头或取消固定。 private const int DbtCustomEvent = 0x8006; //自定义的事件发生。 的Windows NT 4.0和Windows 95:此值不支持。 private const int DbtDeviceQueryRemove = 0x8001; //审批要求删除一个设备或媒体作品。任何应用程序也不能否认这一要求,并取消删除。 private const int DbtDeviceQueryRemoveFailed = 0x8002; //请求删除一个设备或媒体片已被取消。 private const int DbtDeviceRemoveComplete = 0x8004; //一个设备或媒体片已被删除。 private const int DbtDeviceRemovePending = 0x8003; //一个设备或媒体一块即将被删除。不能否认的。 private const int DbtDeviceTypeSpecific = 0x8005; //一个设备特定事件发生。 private const int DbtDevNodesChanged = 0x0007; //一种设备已被添加到或从系统中删除。 private const int DbtQueryChangeConfig = 0x0017; //许可是要求改变目前的配置(码头或取消固定)。 private const int DbtUserDefined = 0xFFFF; //此消息的含义是用户定义的 public static string[] GetRemovableDrivers(ref Message m) { try { if (m.Msg != WmDeviceChange) return null; switch (m.WParam.ToInt32()) { case WmDeviceChange: break; case DbtDeviceArrival://检测到U盘插入 case DbtDeviceRemoveComplete: //检测到U盘拔出 var driveInfos = DriveInfo.GetDrives(); var flashDisks = from driveInfo in driveInfos where driveInfo.DriveType == DriveType.Removable select driveInfo.Name; return flashDisks.ToArray(); case DbtConfigChangeCanceled: break; case DbtConfigchanged: break; case DbtCustomEvent: break; case DbtDeviceQueryRemove: break; case DbtDeviceQueryRemoveFailed: break; case DbtDeviceRemovePending: break; case DbtDeviceTypeSpecific: break; case DbtQueryChangeConfig: break; case DbtUserDefined: break; } } catch (Exception ex) { MessageBox.Show(ex.Message); } return null; } } }在窗体中调用,重写窗体的protected override void WndProc(ref Message m)函数:
protected override void WndProc(ref Message m) { base.WndProc(ref m); try { var aa = FlashDisk.GetRemovableDrivers(ref m); if (aa == null || aa.Length < 1) return; var ds = string.Empty; for (int i = 0; i < aa.Length; i++) { ds += aa[i] + Environment.NewLine; } Console.WriteLine(ds); } catch (Exception ex) { MessageBox.Show(ex.Message); } }运行中发行如果把base.WndProc(ref m);这行代码放到最下面,运行中报错“创建窗口句柄失败”。原来if (aa == null || aa.Length < 1) return;这个代码导致``base.WndProc(ref m);不能总是得到执行。分析得知窗口的句柄创建是通过这行代码创建的。
在定时器中直接调用DriveInfo.GetDrives()函数通过判断driveInfo.DriveType == DriveType.Removable实时性更好