参考:https://docs.microsoft.com/zh-cn/windows/desktop/DevIO/device-management-messages
1、编写USBMonitor处理事件
using System.IO;
class USBMonitor
{
public const int WM_DEVICECHANGE = 0x219; //系统硬件改变发出的系统消息
public const int DBT_CONFIGCHANGECANCELED = 0x0019;
public const int DBT_DEVICEARRIVAL = 0x8000; //系统检测到设备已经插入,并且已经处于可用转态
public const int DBT_DEVICEQUERYREMOVE = 0x8001;
public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
public const int DBT_DEVICEREMOVEPENDING = 0x8003;
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004; //系统检测到设备已经卸载或者拔出
public const int DBT_QUERYCHANGSPECIFIC = 0x8005;
public const int DBT_CUSTOMEVENT = 0x8006;
public const int DBT_DEVICETYPEHANGED = 0x0007;
public const int DBT_DEVNODES_CECONFIG = 0x0017;
public const int DBT_CONFIGCHANGED = 0x0018;
public const int DBT_USERDEFINED = 0xFFFF; //用户自定义消息
/// <summary>
/// 扫描U盘事件
/// </summary>
public static void ScanUDisk(ref System.Windows.Forms.Message m)
{
//Windows系统消息类型:设备改变
if (m.Msg == WM_DEVICECHANGE)
{
//获取具体的设备事件类型
switch (m.WParam.ToInt32())
{
//设备插入事件
case DBT_DEVICEARRIVAL:
Console.WriteLine("检测到设备已经插入");
DriveInfo[] s = DriveInfo.GetDrives();
foreach (DriveInfo drive in s)
{
if (drive.DriveType == DriveType.Removable)
{
Console.WriteLine(string.Format("U盘已插入,盘符是" + drive.Name.ToString()));
break;
}
}
break;
//设备卸载事件
case DBT_DEVICEREMOVECOMPLETE:
Console.WriteLine("检测到设备卸载");
break;
}
}
}
2、在主窗体重写Windows消息处理方法
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void WndProc(ref Message m)
{
//打印所有Windows消息
Console.WriteLine(string.Format("Windows Message:HWnd = {0} LParam = {1} Msg = {2} Result = {3} WParam = {4}", m.HWnd, m.LParam, m.Msg, m.Result, m.WParam));
//检测USB设备类:U盘插拔
USBMonitor.ScanUDisk(ref m);
base.WndProc(ref m);
base.WndProc(ref m);
}
}
测试结果: