C# 监测插入U盘程序和读取当前各类别盘符
在你的类中加入下面的程序。
public const int WM_DEVICECHANGE = 0x219; public const int DBT_DEVICEARRIVAL = 0x8000; public const int DBT_CONFIGCHANGECANCELED = 0x0019; public const int DBT_CONFIGCHANGED = 0x0018; public const int DBT_CUSTOMEVENT = 0x8006; public const int DBT_DEVICEQUERYREMOVE = 0x8001; public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002; public const int DBT_DEVICEREMOVECOMPLETE = 0x8004; public const int DBT_DEVICEREMOVEPENDING = 0x8003; public const int DBT_DEVICETYPESPECIFIC = 0x8005; public const int DBT_DEVNODES_CHANGED = 0x0007; public const int DBT_QUERYCHANGECONFIG = 0x0017; public const int DBT_USERDEFINED = 0xFFFF; [StructLayout(LayoutKind.Sequential)] public struct DEV_BROADCAST_VOLUME { public int dbcv_size; public int dbcv_devicetype; public int dbcv_reserved; public int dbcv_unitmask; } protected override void WndProc(ref Message m) { try { if (m.Msg == WM_DEVICECHANGE) { switch (m.WParam.ToInt32()) { case WM_DEVICECHANGE: break; case DBT_DEVICEARRIVAL://U盘插入 DriveInfo[] s = DriveInfo.GetDrives(); foreach (DriveInfo drive in s) { if (drive.DriveType == DriveType.Removable) { string text1 = "U盘已插入,盘符为:" + drive.Name.ToString(); break; } } break; case DBT_CONFIGCHANGECANCELED: break; case DBT_CONFIGCHANGED: break; case DBT_CUSTOMEVENT: break; case DBT_DEVICEQUERYREMOVE: break; case DBT_DEVICEQUERYREMOVEFAILED: break; case DBT_DEVICEREMOVECOMPLETE: //U盘卸载 string text = ""; break; case DBT_DEVICEREMOVEPENDING: break; case DBT_DEVICETYPESPECIFIC: break; case DBT_DEVNODES_CHANGED: break; case DBT_QUERYCHANGECONFIG: break; case DBT_USERDEFINED: break; default: break; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } base.WndProc(ref m); }
查找当前磁盘中各类别的盘符
/// <summary> /// 读取所有USB磁盘盘符列表 /// </summary> /// <returns></returns> private List<string> ReadUsbDrive() { List<string> driveNames = new List<string>(); SelectQuery sq = new SelectQuery("select * from win32_logicaldisk"); System.Management.ManagementObjectSearcher mos = new ManagementObjectSearcher(sq); foreach (System.Management.ManagementObject disk in mos.Get()) { //Name表示设备的名称 //各属性的标识见联机的MSDN里,Win32 and COM Development下的WMI。 //如http://msdn.microsoft.com/en-us/library/aa394173(VS.85).aspx try { string strType = disk["DriveType"].ToString(); switch (strType) //类型 { case "0": //未知设备 break; case "1": //未分区 break; case "2": //可移动磁盘 driveNames.Add(disk["Name"].ToString()); break; case "3": //硬盘 break; case "4": //网络驱动器 break; case "5": //光驱" break; case "6": //内存磁盘 break; } } catch { //item.SubItems.Add("设备未准备好"); } } return driveNames; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步