Is Usb Drive () ? DeviceIoControl, IOCTL_STORAGE_QUERY_PROPERTY

http://banderlogi.blogspot.com/2011/06/enum-drive-letters-attached-for-usb.html

typedef enum _STORAGE_BUS_TYPE { 
  BusTypeUnknown      = 0x00,
  BusTypeScsi         = 0x01,
  BusTypeAtapi        = 0x02,
  BusTypeAta          = 0x03,
  BusType1394         = 0x04,
  BusTypeSsa          = 0x05,
  BusTypeFibre        = 0x06,
  BusTypeUsb          = 0x07,
  BusTypeRAID         = 0x08,
  BusTypeiSCSI        = 0x09,
  BusTypeSas          = 0x0A,
  BusTypeSata         = 0x0B,
  BusTypeMaxReserved  = 0x7F
} STORAGE_BUS_TYPE, *PSTORAGE_BUS_TYPE;
typedef struct _STORAGE_DEVICE_DESCRIPTOR {
  DWORD            Version;
  DWORD            Size;
  BYTE             DeviceType;
  BYTE             DeviceTypeModifier;
  BOOLEAN          RemovableMedia;
  BOOLEAN          CommandQueueing;
  DWORD            VendorIdOffset;
  DWORD            ProductIdOffset;
  DWORD            ProductRevisionOffset;
  DWORD            SerialNumberOffset;
  STORAGE_BUS_TYPE BusType;
  DWORD            RawPropertiesLength;
  BYTE             RawDeviceProperties[1];
} STORAGE_DEVICE_DESCRIPTOR, *PSTORAGE_DEVICE_DESCRIPTOR;
bool IsUsbDevice( wchar_t letter )
{
  wchar_t volumeAccessPath[ ] = L"\\.\X:";
  volumeAccessPath[ 4 ] = letter;

  HANDLE deviceHandle = CreateFileW( volumeAccessPath, 0, // no access to the drive
    FILE_SHARE_READ | // share mode
      FILE_SHARE_WRITE, NULL,             // default security attributes
    OPEN_EXISTING,    // disposition
    0,                // file attributes
    NULL );            // do not copy file attributes

  // setup query
  STORAGE_PROPERTY_QUERY query;
  memset( &query, 0, sizeof( query ) );
  query.PropertyId = StorageDeviceProperty;
  query.QueryType = PropertyStandardQuery;

  // issue query
  DWORD bytes;
  STORAGE_DEVICE_DESCRIPTOR devd;
  STORAGE_BUS_TYPE busType = BusTypeUnknown;

  if ( DeviceIoControl( deviceHandle, IOCTL_STORAGE_QUERY_PROPERTY, &query,
    sizeof( query ), &devd, sizeof( devd ), &bytes, NULL ) )
  {
    busType = devd.BusType;
  }
  else
  {
    std
  ::wcout << L"Failed to define bus type for: " << letter;
}

CloseHandle( deviceHandle );

return BusTypeUsb == busType;
}
原文地址:https://www.cnblogs.com/shangdawei/p/3163970.html