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
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. :)