无法使用C ++中的Windows服务检索可移动设备上的数据

时间:2012-01-04 09:54:51

标签: c++ visual-studio-2010 service

我正在尝试检测可移动设备的插入并使用NT服务检索所述设备的驱动器号。我已成功检测到设备的插入和删除,但无法设置DEV_BROADCAST_VOLUME结构,这样我就可以从卷中获取驱动器号,GUID等。

case SERVICE_CONTROL_DEVICEEVENT:{
            switch(evtype){
            case DBT_DEVICEARRIVAL:{
                    DEV_BROADCAST_VOLUME *hdr = (DEV_BROADCAST_VOLUME*) evdata;
                    ofstream log ("C:\\log.txt", ios::app);
                    log << hdr->dbcv_devicetype;
                    log.close();
                }
                break;

上面的代码段正确编译并运行,但是当我插入闪存驱动器时,hdr->dbcv_devicetype会记录为55555DBT_DEVTYP_VOLUME(这是USB驱动器的值)被定义为2hdr->dbcv_devicetype应该等于DBT_DEVTYP_VOLUME,因为我插入了一个闪存驱动器)。出于某种原因,DBT_DEVTYP_VOLUME没有正确初始化,或者我正在做的其他事情是错误的。我在Windows 7中使用Visual Studio 2011 C ++。

1 个答案:

答案 0 :(得分:1)

试试这个:

  PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)evdata;
  if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLUME)
   {
    PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;

    if (lpdbv -> dbcv_flags & DBTF_MEDIA)
     {
      StringCchPrintf( szMsg, sizeof(szMsg)/sizeof(szMsg[0]), 
                       TEXT("Drive %c: Media has arrived.\n"), 
                       FirstDriveFromMask(lpdbv ->dbcv_unitmask) );

      MessageBox( hwnd, szMsg, TEXT("WM_DEVICECHANGE"), MB_OK );
     }
   }

   /*------------------------------------------------------------------
      FirstDriveFromMask( unitmask )

      Description
        Finds the first valid drive letter from a mask of drive letters.
        The mask must be in the format bit 0 = A, bit 1 = B, bit 2 = C, 
        and so on. A valid drive letter is defined when the 
        corresponding bit is set to 1.

      Returns the first drive letter that was found.
   --------------------------------------------------------------------*/

   char FirstDriveFromMask( ULONG unitmask )
    {
     char i;

     for (i = 0; i < 26; ++i)
      {
       if (unitmask & 0x1)
         break;
       unitmask = unitmask >> 1;
      }

     return( i + 'A' );
   }

代码来自Detecting Media Insertion or Removal