C#检测是否有u盘插入的方法
本文实例讲述了C#检测是否有u盘插入的方法。分享给大家供大家参考。具体如下:
该C#代码可监控是否有u盘插入,同时可以监控其它驱动器的变化
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices ; namespace WindowsApplication16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } [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) { // 发生设备变动 const int WM_DEVICECHANGE = 0x0219; // 系统检测到一个新设备 const int DBT_DEVICEARRIVAL = 0x8000; // 系统完成移除一个设备 const int DBT_DEVICEREMOVECOMPLETE = 0x8001; // 逻辑卷标 const int DBT_DEVTYP_VOLUME = 0x00000002; switch (m.Msg) { case WM_DEVICECHANGE: switch (m.WParam.ToInt32()) { case DBT_DEVICEARRIVAL: int devType = Marshal.ReadInt32(m.LParam, 4); if (devType == DBT_DEVTYP_VOLUME) { DEV_BROADCAST_VOLUME vol; vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure( m.LParam, typeof(DEV_BROADCAST_VOLUME)); MessageBox.Show(vol.dbcv_unitmask.ToString("x")); } break; case DBT_DEVICEREMOVECOMPLETE: MessageBox.Show("Removal"); break; } break; } base.WndProc(ref m); } } }
希望本文所述对大家的C#程序设计有所帮助。
赞 (0)