关键实现1:
扫描所有存储设备,筛选出U盘
private void ScanDisk() { DriveInfo[] drives = DriveInfo.GetDrives(); foreach (var drive in drives) { // 可移动存储设备,且不是A盘 if ((drive.DriveType == DriveType.Removable) && false == drive.Name.Substring(0, 1).Equals("A")) { Console.WriteLine("找到一个U盘:" + drive.Name); } } }
关键实现2:
监听系统消息,在加载U盘时处理
const int WM_DeviceChange = 0x219; // 系统硬件改变发出的系统消息 const int DBT_DeviceArrival = 0x8000; // 设备检测结束,并可以使用 const int DBT_DeviceRemoveComplete = 0x8004;// 设备移除 protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_DeviceChange) // 系统硬件改变发出的系统消息 { switch (m.WParam.ToInt32()) { case WM_DeviceChange: break; case DBT_DeviceArrival: ScanDisk(); // 扫描所有满足特征的设备 break; case DBT_DeviceRemoveComplete: ScanDisk(); break; default: break; } } }
扩展:相关的消息列表
const int DBT_ConfigChangeCanceled = 0x0019; const int DBT_ConfigChanged = 0x0018; const int DBT_CustomEvent = 0x8006; const int DBT_DeviceQueryRemove = 0x8001; const int DBT_DeviceQueryRemoveFailed = 0x8002; const int DBT_DeviceRemovePending = 0x8003; const int DBT_DeviceTypeHanged = 0x8007; const int DBT_QueryChangSpecific = 0x8005; const int DBT_DevNodes_CEConfig = 0x0017; const int DBT_UserDefined = 0xFFFF;