相同HID设备的句柄获取

思路其实很简单:通常我们使用PID和VID来获得不同设备的句柄,相同PID和VID的设备,就需要其他的特征来获取句柄。相同HID的设备,设备路径是不同的,可以用设备路径作为区分,来获得句柄即可。

HANDLE OpenSamePIDDevice(int overlapped, unsigned short Pid_Value)
{
	int Pid_count = 0;
	LPCWSTR device_path = NULL;


	HANDLE hidHandle = NULL;
	HidD_GetHidGuid(&hidGuid); //取得类别 
	HDEVINFO hDevInfo = SetupDiGetClassDevs(&hidGuid, NULL, NULL,
		(DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));  //获取设备信息群

	if (hDevInfo == INVALID_HANDLE_VALUE)//未获得设备信息群则直接退出
		return INVALID_HANDLE_VALUE;

	SP_DEVICE_INTERFACE_DATA devInfoData;
	devInfoData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
	int deviceNo = 0;
	SetLastError(NO_ERROR);

	while (GetLastError() != ERROR_NO_MORE_ITEMS)
	{
		if (SetupDiEnumInterfaceDevice(hDevInfo, 0, &hidGuid, deviceNo, &devInfoData)) //枚举成功?
		{
			ULONG requiredLength = 0;
			SetupDiGetInterfaceDeviceDetail(hDevInfo, &devInfoData, NULL, 0, &requiredLength, NULL);//获得接口详细信息
			PSP_INTERFACE_DEVICE_DETAIL_DATA devDetail = (SP_INTERFACE_DEVICE_DETAIL_DATA*)malloc(requiredLength);
			devDetail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
			if (!SetupDiGetInterfaceDeviceDetail(hDevInfo, &devInfoData, devDetail, requiredLength, NULL, NULL))//获得详细信息失败则退出
			{
				free(devDetail);
				SetupDiDestroyDeviceInfoList(hDevInfo);
				return INVALID_HANDLE_VALUE;
			}

			if (overlapped) //打开设备
			{
				hidHandle = CreateFile(devDetail->DevicePath,
					GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
					NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
			}
			else
			{
				hidHandle = CreateFile(devDetail->DevicePath,
					GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
					NULL, OPEN_EXISTING, 0, NULL);
			}
			//if (devDetail != NULL)
			//free(devDetail);
			if (hidHandle == INVALID_HANDLE_VALUE)
			{
				SetupDiDestroyDeviceInfoList(hDevInfo);
				//	free(devDetail);
				return INVALID_HANDLE_VALUE;
			}
			_HIDD_ATTRIBUTES hidAttributes;
			if (!HidD_GetAttributes(hidHandle, &hidAttributes))
			{
				CloseHandle(hidHandle);
				SetupDiDestroyDeviceInfoList(hDevInfo);
				return INVALID_HANDLE_VALUE;
			}

			if ((USB_VID == hidAttributes.VendorID)&(Pid_Value == hidAttributes.ProductID))   //仅仅根据VID进行STM32设备判断
			{
				++Pid_count;

				if (Pid_count == 1)
				{ 			
					//获得句柄
					if(Pid_Value == Handset_PID)
					{ 
					hHandSet1 = hidHandle;
					}
					else if(Pid_Value == Camera_PID)
					{
					hCamera1 = hidHandle;
					}
					device_path = devDetail->DevicePath;//用于路径比较
				}
				if ((Pid_count != 1)&(device_path!= devDetail->DevicePath))
				{ 
					if (Pid_Value == Handset_PID)
					{
						hHandSet2 = hidHandle;
					}
					else if (Pid_Value == Camera_PID)
					{
						hCamera2 = hidHandle;
					}
			
				    break;
				}
				


				//CloseHandle(hidHandle);
				++deviceNo;


				
			}
			else
			{
				CloseHandle(hidHandle);
				++deviceNo;
			}
		}
	}
	SetupDiDestroyDeviceInfoList(hDevInfo);
	return hidHandle;
}

 

 

 

 

 

你可能感兴趣的:(MFC,USB)