简体   繁体   中英

How to read file from USB mass storage Device using Visual C++?

I developed an MFC Dialog application in C++ in MS VS 2013 Ultimate under Windows 7 Maximal. As a progenitor of source code I use CodeProject paper in Detecting Hardware Insertion or Removal .

My application is a user-mode application. It is intended for detection of adding or removing hardware from/to computer. For this purpose I handle WM_DEVICECHANGE message and call RegisterDeviceNotification() function in my application. So, schematically, my aplication does the following:

  1. Calls SetupDiGetClassDevs() to get a handle of device info set HDEVINFO .
  2. Calls SetupDiEnumDeviceInfo() to enumerate all the device in the info set. Upon each iteration, we will get a SP_DEVINFO_DATA .
  3. During the enumeration, SetupDiGetDeviceInstanceId() is called to read the instance ID for each device. The instance ID is in the form of "USB\\Vid_04e8&Pid_503b\\0002F9A9828E0F06".
  4. If the instance ID match the DEV_BROADCAST_DEVICEINTERFACE.dbcc_name , then SetupDiGetDeviceRegistryProperty() is called to retrieve the description or friendly name.

But now I'm in need of reading of file from USB mass storage device when this device is pluged in (when the DBT_DEVICEARRIVAL device event has place). How can I do it programmatically in Visual C++?

The parameter of DBT_DEVICEARRIVAL is a DEV_BROADCAST_VOLUME which includes a mask of the drive letter assinged. So since you are only after mass storage devices the following works.

DEV_BROADCAST_VOLUME *pj = (DEV_BROADCAST_VOLUME*) lParam;
if (pj->dbcv_devicetype == DBT_DEVTYPE_VOLUME) {
    long um = pj->dbcv_unitmask;
    for ( int i=0; i < 26; i++ ) {
        if (um&1) break;
        um = um >> 1;
    }

    if ( i < 26 ) {
        char Drive  = 'A' + i;
    }
}

In practice, some drives are ready to read instantly, others need few seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM