C#检测是否有u盘插入的方法
本文实例讲述了C#检测是否有u盘插入的方法。分享给大家供大家参考。具体如下:
该C#代码可监控是否有u盘插入,同时可以监控其它驱动器的变化
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Runtime.InteropServices
;
namespaceWindowsApplication16
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
}
[StructLayout(LayoutKind.Sequential)]
publicstructDEV_BROADCAST_VOLUME
{
publicintdbcv_size;
publicintdbcv_devicetype;
publicintdbcv_reserved;
publicintdbcv_unitmask;
}
protectedoverridevoidWndProc(refMessagem)
{
//发生设备变动
constintWM_DEVICECHANGE=0x0219;
//系统检测到一个新设备
constintDBT_DEVICEARRIVAL=0x8000;
//系统完成移除一个设备
constintDBT_DEVICEREMOVECOMPLETE=0x8001;
//逻辑卷标
constintDBT_DEVTYP_VOLUME=0x00000002;
switch(m.Msg)
{
caseWM_DEVICECHANGE:
switch(m.WParam.ToInt32())
{
caseDBT_DEVICEARRIVAL:
intdevType=Marshal.ReadInt32(m.LParam,4);
if(devType==DBT_DEVTYP_VOLUME)
{
DEV_BROADCAST_VOLUMEvol;
vol=(DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(
m.LParam,typeof(DEV_BROADCAST_VOLUME));
MessageBox.Show(vol.dbcv_unitmask.ToString("x"));
}
break;
caseDBT_DEVICEREMOVECOMPLETE:
MessageBox.Show("Removal");
break;
}
break;
}
base.WndProc(refm);
}
}
}
希望本文所述对大家的C#程序设计有所帮助。