Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1683282
  • 博文数量: 584
  • 博客积分: 13857
  • 博客等级: 上将
  • 技术积分: 11883
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-16 09:34

分类: WINDOWS

2011-03-22 10:58:37

只要你程序运行着,一旦有U盘插入,操作系统(我指的是Windows OS)会向每个进程广播WM_DEVICECHANGE消息的,只要响应该消息就可以了
  1. // 优盘插入

  2. public const int WM_DEVICECHANGE = 0x219;
  3. public const int DBT_DEVICEARRIVAL = 0x8000;
  4. public const int DBT_CONFIGCHANGECANCELED = 0x0019;
  5. public const int DBT_CONFIGCHANGED = 0x0018;
  6. public const int DBT_CUSTOMEVENT = 0x8006;
  7. public const int DBT_DEVICEQUERYREMOVE = 0x8001;
  8. public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
  9. public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
  10. public const int DBT_DEVICEREMOVEPENDING = 0x8003;
  11. public const int DBT_DEVICETYPESPECIFIC = 0x8005;
  12. public const int DBT_DEVNODES_CHANGED = 0x0007;
  13. public const int DBT_QUERYCHANGECONFIG = 0x0017;
  14. public const int DBT_USERDEFINED = 0xFFFF;

  15. protected override void WndProc(ref Message m)
  16. {
  17.   try
  18.   {
  19.     if (m.Msg == WM_DEVICECHANGE)
  20.     {
  21.       switch (m.WParam.ToInt32())
  22.       {
  23.         case WM_DEVICECHANGE:
  24.           break;
  25.         case DBT_DEVICEARRIVAL://U盘插入
  26.           DriveInfo[] s = DriveInfo.GetDrives();
  27.           foreach (DriveInfo drive in s)
  28.           {
  29.             if (drive.DriveType == DriveType.Removable)
  30.             {
  31.               Upath = drive.Name.ToString();
  32.               string folderpath = Upath + @"\taxbase";
  33.               if (!Directory.Exists(folderpath))
  34.               {
  35.                 Directory.CreateDirectory(folderpath);
  36.               }
  37.               string path = Upath + @"\taxbase\" + LoginUserInfo.LoginUser.Com_code + @".db";
  38.               if (File.Exists(path))
  39.               {
  40.                 MessageBox.Show("检测到U盘插入,可以更新数据!
  41.               }
                  break;
                }
              }
              break;
            case DBT_CONFIGCHANGECANCELED:
              break;
            case DBT_CONFIGCHANGED:
              break;
            case DBT_CUSTOMEVENT:
              break;
            case DBT_DEVICEQUERYREMOVE:
              break;
            case DBT_DEVICEQUERYREMOVEFAILED:
              break;
            case DBT_DEVICEREMOVECOMPLETE: //U盘卸载
              break;
            case DBT_DEVICEREMOVEPENDING:
              break;
            case DBT_DEVICETYPESPECIFIC:
              break;
            case DBT_DEVNODES_CHANGED:
              break;
            case DBT_QUERYCHANGECONFIG:
              break;
            case DBT_USERDEFINED:
              break;
            default:
              break;
          }
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
      base.WndProc(ref m);
    }

阅读(703) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~