这个简单的 C++ 代码可以检测任何笔式驱动器、存储卡和外部硬盘驱动器-
#include <stdio.h>
#include <time.h>
#include <windows.h>
#include <string>
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; i < dwResult; i++) {
if (szLogicalDrives[i] > 64 && szLogicalDrives[i] < 90) {
currentDrives.append(1, szLogicalDrives[i]);
if (allDrives.find(szLogicalDrives[i]) > 100) {
drive = szLogicalDrives[i];
}
}
}
allDrives = currentDrives;
return drive;
}
Run Code Online (Sandbox Code Playgroud)
PS:此代码片段可以检测Windows操作系统的一个新USB存储设备的插入。如果 1 秒内同时插入多个设备,则只会检测到一个。但是,当然,您也可以通过少量代码更改来实现多重检测。:)