隐藏

C#监控U盘插拔

发布:2024/5/5 21:13:59作者:管理员 来源:本站 浏览次数:91

【1】涉及的知识点


1) windows消息处理函数


protected override void WndProc(ref Message m)


捕获Message的系统硬件改变发出的系统消息


2) 硬件信息类


DriveInfo


关键实现1:


   扫描所有存储设备,筛选出U盘


private void ScanDisk()

       {

           DriveInfo[] drives = DriveInfo.GetDrives();

           foreach (var drive in drives)

           {

               // 可移动存储设备,且不是A盘

               if ((drive.DriveType == DriveType.Removable) && false == drive.Name.Substring(0, 1).Equals("A"))

               {

                   Console.WriteLine("找到一个U盘:" + drive.Name);

               }

           }

       }



关键实现2:


   监听系统消息,在加载U盘时处理



const int WM_DeviceChange = 0x219;   // 系统硬件改变发出的系统消息

       const int DBT_DeviceArrival = 0x8000;   // 设备检测结束,并可以使用

       const int DBT_DeviceRemoveComplete = 0x8004;// 设备移除


       protected override void WndProc(ref Message m)

       {

           base.WndProc(ref m);


           if (m.Msg == WM_DeviceChange) // 系统硬件改变发出的系统消息

           {

               switch (m.WParam.ToInt32())

               {

                   case WM_DeviceChange:

                       break;

                   case DBT_DeviceArrival:

                       ScanDisk(); // 扫描所有满足特征的设备

                       break;

                   case DBT_DeviceRemoveComplete:

                       ScanDisk();

                       break;

                   default:

                       break;

               }

           }

       }