该C#代码实现监控USB接口是否有设备接入或拨出,包括多个U盘。
1 using System; 2 using System.IO; 3 using System.Runtime.InteropServices; 4 using System.Windows.Forms; 5 6 namespace MyApplication 7 { 8 public partial class Form1 : Form 9 { 10 const int WM_DEVICECHANGE = 0x0219; // 发生设备变动 11 const int DBT_DEVICEARRIVAL = 0x8000; // 系统检测到一个新设备 12 const int DBT_DEVTYP_VOLUME = 0x00000002; // 逻辑卷标 13 const int DBT_CONFIGCHANGECANCELED = 0x0019; 14 const int DBT_CONFIGCHANGED = 0x0018; 15 const int DBT_CUSTOMEVENT = 0x8006; 16 const int DBT_DEVICEQUERYREMOVE = 0x8001; 17 const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002; // 系统完成移除一个设备 18 const int DBT_DEVICEREMOVECOMPLETE = 0x8004; 19 const int DBT_DEVICEREMOVEPENDING = 0x8003; 20 const int DBT_DEVICETYPESPECIFIC = 0x8005; 21 const int DBT_DEVNODES_CHANGED = 0x0007; 22 const int DBT_QUERYCHANGECONFIG = 0x0017; 23 const int DBT_USERDEFINED = 0xFFFF; 24 25 [StructLayout(LayoutKind.Sequential)] 26 public struct DEV_BROADCAST_VOLUME 27 { 28 public int dbcv_size; 29 public int dbcv_devicetype; 30 public int dbcv_reserved; 31 public int dbcv_unitmask; 32 } 33 34 public Form1() 35 { 36 InitializeComponent(); 37 } 38 39 protected override void WndProc(ref Message m) 40 {