首先,定义USB相关驱动的消息常量,如下,其中WM_DEVICECHANGE表示有设备发生变化,对USB插入和拔出事件来说,只有只需要定义两个:DBT_DEVICEARRIVAL(插入设备)和DBT_DEVICEREMOVECOMPLETE(拔出设备)。所有的消息常量如下:
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;
定义好消息常量之后,需要重写WndProc,如下:
protected override void WndProc(ref Message m)
{
try
{
if (m.Msg == WM_DEVICECHANGE)
{
switch (m.WParam.ToInt32())
{
case DBT_DEVICEARRIVAL:
//USB插入时要处理的事件
break;
case DBT_DEVICEREMOVECOMPLETE:
//USB拔出时要处理的事件
break;
default:
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
base.WndProc(ref m);
}
重写代码时只列出了USB插入和拔出时处理方法,如果想添加其他的可以依照这两个添加。
如果想获取插入可移动设备的盘符,可以用以下代码:
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable)
{
Text = "盘符:" + drive.Name.ToString();
break;
}
}