Winform检查USB设备变动,检测U盘插拔

实现原理

Windows操作系统会在设备状态发生变化时发送系统消息,我们可以通过重写Form的WndProc方法来捕获这些消息,从而实现对USB设备变动的检测。

1. 定义消息常量

public const int WM_DEVICECHANGE = 0x219;               //系统硬件改变发出的系统消息
public const int DBT_DEVICEARRIVAL = 0x8000;            //系统检测到设备已经插入,并且已经处于可用转态
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;     //系统检测到设备已经卸载或者拔出

2. 重写WndProc方法

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盘插拔
    ScanUDisk(ref m);

    base.WndProc(ref m);
}

3. 实现ScanUDisk方法

/// <summary>
/// 扫描U盘事件
/// </summary>
public void ScanUDisk(ref System.Windows.Forms.Message m)
{
    //Windows系统消息类型:设备改变
    if (m.Msg == WM_DEVICECHANGE)
    {
        //获取具体的设备事件类型
        switch (m.WParam.ToInt32())
        {
            //设备插入事件
            case DBT_DEVICEARRIVAL:
                
                Console.WriteLine("检测到设备已经插入");
                textBox1.AppendText("检测到设备已经插入\r\n");
                DriveInfo[] s = DriveInfo.GetDrives();
                foreach (DriveInfo drive in s)
                {
                    if (drive.DriveType == DriveType.Removable)
                    {
                        Console.WriteLine(string.Format("U盘已插入,盘符是" + drive.Name));
                        textBox1.AppendText(string.Format("U盘已插入,盘符是\r\n" + drive.Name));
                        break;
                    }
                }
                break;
            //设备卸载事件
            case DBT_DEVICEREMOVECOMPLETE:
                Console.WriteLine("检测到设备卸载");
                textBox1.AppendText("检测到设备卸载\r\n");
                break;
        }
    }
}
posted @ 2026-04-15 17:06  (*_^)?  阅读(30)  评论(0)    收藏  举报