How do I detected whether a hard drive is connected via USB?

后端 未结 5 1569
无人及你
无人及你 2021-01-01 06:52

I am trying to write a little backup program for friends and family and want it to be as simple to use a possible. I don\'t want to have to ask the user where to backup thei

5条回答
  •  旧时难觅i
    2021-01-01 07:16

    I spent a little time looking around and found a function called SetupDiEnumDeviceInfo which did provide a solution to know whether a hard drive was removable or not but with that information I still can't (yet) map what I find back to a drive letter!

    Here's what I have so far (following code creates a dll):

    #include "stdafx.h"
    #include 
    #include 
    #include 
    extern "C" __declspec(dllexport) int usb_hard_drives() {
      HDEVINFO hdevinfo = SetupDiGetClassDevs(&GUID_DEVCLASS_DISKDRIVE, NULL, NULL, DIGCF_PRESENT);
      if (hdevinfo == INVALID_HANDLE_VALUE) return -1;
      DWORD MemberIndex = 0;
      SP_DEVINFO_DATA sp_devinfo_data;
      ZeroMemory(&sp_devinfo_data, sizeof(sp_devinfo_data));
      sp_devinfo_data.cbSize = sizeof(sp_devinfo_data);
      int c = 0;
      while (SetupDiEnumDeviceInfo(hdevinfo, MemberIndex, &sp_devinfo_data)) {
        DWORD PropertyRegDataType;
        DWORD RequiredSize;
        DWORD PropertyBuffer;
        if (SetupDiGetDeviceRegistryProperty(hdevinfo, &sp_devinfo_data, SPDRP_CAPABILITIES, &PropertyRegDataType, (PBYTE)&PropertyBuffer, sizeof(PropertyBuffer), &RequiredSize)) {
          if (PropertyBuffer && CM_DEVCAP_REMOVABLE == CM_DEVCAP_REMOVABLE) {
            // do something here to identify the drive letter.
            c++;
          }
        }       
        MemberIndex++;
      }
      SetupDiDestroyDeviceInfoList(hdevinfo);
      return c;
    }
    

提交回复
热议问题