#include "USBHotPlug.h"
USB_STATE_T detectUsbState(HDEVINFO &devInfoSet, TCHAR* pVid, TCHAR* pPid)
{
TCHAR buffer[MAX_BUFFER_LEN] = {'\0'};
int memberIndex = 0;
while (true) {
SP_DEVINFO_DATA deviceInfoData;
ZeroMemory(&deviceInfoData, sizeof(SP_DEVINFO_DATA));
deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
if (SetupDiEnumDeviceInfo(devInfoSet, memberIndex, &deviceInfoData) == FALSE) {
if (GetLastError() == ERROR_NO_MORE_ITEMS) {
break;
}
}
DWORD nSize = 0;
SetupDiGetDeviceInstanceId(devInfoSet, &deviceInfoData, buffer, sizeof(buffer), &nSize);
/*
for (int i = 0; i < nSize; i++) {
printf("%s", reinterpret_cast(buffer + i));
}
printf("\n");
*/
if(_tcsstr(buffer, pVid) != NULL && _tcsstr(buffer, pPid) != NULL){
return PLUG_IN;
}
memberIndex++;
}
return PLUG_OUT;
}
void init_USB(HDEVINFO &devInfoSet)
{
devInfoSet = SetupDiGetClassDevs((GUID*)&GUID_DEVCLASS_USB, NULL, NULL, DIGCF_PRESENT | DIGCF_PROFILE);
}
void uninit_USB(HDEVINFO &devInfoSet)
{
if (devInfoSet) {
SetupDiDestroyDeviceInfoList(devInfoSet);
}
}
int main(int argc, char **argv)
{
HDEVINFO deviceInfoSet;
init_USB(deviceInfoSet);
if (detectUsbState(deviceInfoSet, "VID_0BDA", "PID_0101") == PLUG_IN) {
printf("plug in\n");
}else{
printf("plug out\n");
}
uninit_USB(deviceInfoSet);
system("pause");
return 0;
}