Detecting USB insertion/Removal in C++ non-GUI application

前端 未结 5 1537
独厮守ぢ
独厮守ぢ 2020-12-14 20:25

I want to detect insertion/removal of a specific (Custom) USB device through a C++ application which runs in background and has no GUI.

I have seen lot of questions

5条回答
  •  离开以前
    2020-12-14 21:12

    External USB Storage Device Detector


    This program (C++) detects pen drive, memory card & external hard drive (whenever a new USB storage device is inserted)-

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    string allDrives;
    
    char getRemovableDisk();
    
    int main(void){
    
        char driveLetter = getRemovableDisk();
        while(1){
            driveLetter = getRemovableDisk();
            if(driveLetter!='0'){
                printf("%c \n", driveLetter);
            }
    
            Sleep(1000);
        }
    
        return 0;
    }
    
    char getRemovableDisk(){
        char drive='0';
    
        char szLogicalDrives[MAX_PATH];
        DWORD dwResult = GetLogicalDriveStrings(MAX_PATH, szLogicalDrives);
    
        string currentDrives="";
    
        //cout << dwResult << endl;
        for(int i=0; i64 && szLogicalDrives[i]< 90)
            {
                currentDrives.append(1, szLogicalDrives[i]);
    
                if(allDrives.find(szLogicalDrives[i]) > 100)
                {
                    drive = szLogicalDrives[i];
                }
            }
        }
    
        allDrives = currentDrives;
    
        return drive;
    }
    

    Remark: This code snippet can detect only one new device (even if more than one is inserted at once). But, of course, you can achieve multiple detection too, with a little change. :)

提交回复
热议问题