/// <summary> /// Gets a list of <see cref="WinUsbRegistry"/> classes for the specified interface guid. /// </summary> /// <param name="deviceInterfaceGuid">The DeviceInterfaceGUID to search for.</param> /// <param name="deviceRegistryList">A list of device paths associated with the <paramref name="deviceInterfaceGuid"/>.</param> /// <returns>True of one or more device paths was found.</returns> /// <remarks> /// Each <see cref="WinUsbRegistry"/> in the <paramref name="deviceRegistryList"/> represents a seperate WinUSB device (interface). /// </remarks> public static bool GetWinUsbRegistryList(Guid deviceInterfaceGuid, out List <WinUsbRegistry> deviceRegistryList) { deviceRegistryList = new List <WinUsbRegistry>(); int devicePathIndex = 0; SetupApi.SP_DEVICE_INTERFACE_DATA interfaceData = SetupApi.SP_DEVICE_INTERFACE_DATA.Empty; SetupApi.DeviceInterfaceDetailHelper detailHelper; SetupApi.SP_DEVINFO_DATA devInfoData = SetupApi.SP_DEVINFO_DATA.Empty; // [1] IntPtr deviceInfo = SetupApi.SetupDiGetClassDevs(ref deviceInterfaceGuid, null, IntPtr.Zero, SetupApi.DICFG.PRESENT | SetupApi.DICFG.DEVICEINTERFACE); if (deviceInfo != IntPtr.Zero) { while ((SetupApi.SetupDiEnumDeviceInterfaces(deviceInfo, null, ref deviceInterfaceGuid, devicePathIndex, ref interfaceData))) { int length = 1024; detailHelper = new SetupApi.DeviceInterfaceDetailHelper(length); bool bResult = SetupApi.SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, detailHelper.Handle, length, out length, ref devInfoData); if (bResult) { WinUsbRegistry regInfo = new WinUsbRegistry(); SetupApi.getSPDRPProperties(deviceInfo, ref devInfoData, regInfo.mDeviceProperties); // Use the actual winusb device path for SYMBOLIC_NAME_KEY. This will be used to open the device. regInfo.mDeviceProperties.Add(SYMBOLIC_NAME_KEY, detailHelper.DevicePath); #if VERY_DEBUG Debug.WriteLine(detailHelper.DevicePath); #endif regInfo.mDeviceInterfaceGuids = new Guid[] { deviceInterfaceGuid }; StringBuilder sbDeviceID = new StringBuilder(1024); if (SetupApi.CM_Get_Device_ID(devInfoData.DevInst, sbDeviceID, sbDeviceID.Capacity, 0) == SetupApi.CR.SUCCESS) { regInfo.mDeviceProperties[DEVICE_ID_KEY] = sbDeviceID.ToString(); } deviceRegistryList.Add(regInfo); } devicePathIndex++; } } if (devicePathIndex == 0) { UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetDevicePathList", typeof(SetupApi)); } if (deviceInfo != IntPtr.Zero) { SetupApi.SetupDiDestroyDeviceInfoList(deviceInfo); } return(devicePathIndex > 0); }
public static int EnumerateDevices(DeviceEnumeratorInfo deviceEnumeratorInfo) { int devIndex; const uint CM_PROB_PHANTOM = (0x0000002D); // The devinst currently exists only in the registry // Initialize the SP_DEVINFO_DATA structure SetupApi.SP_DEVINFO_DATA devInfoData = new SetupApi.SP_DEVINFO_DATA(); devInfoData.cbSize = (uint)Marshal.SizeOf(typeof(SetupApi.SP_DEVINFO_DATA)); // Used to parse the DeviceID tokens. RegHardwareID regHardwareID = RegHardwareID.GlobalInstance; // Used as a buffer for: // * SetupDiGetDeviceRegistryProperty // * CM_Get_Device_ID // * SetupDiGetCustomDeviceProperty // * SetupDiGetDeviceProperty byte[] propBuffer = new byte[1024]; // List all connected USB devices IntPtr pDevInfo = SetupApi.SetupDiGetClassDevs(0, "USB", deviceEnumeratorInfo.Hwnd, deviceEnumeratorInfo.DICFGFlags); if (pDevInfo == IntPtr.Zero || pDevInfo == new IntPtr(-1)) { InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Win32Error, "SetupDiGetClassDevs Failed!"); return(-1); } for (devIndex = 0;; devIndex++) { if (!SetupApi.SetupDiEnumDeviceInfo(pDevInfo, devIndex, ref devInfoData)) { // Reached the end of the eviceInfo list. InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Info, "device enumeration complete."); break; } DeviceItem deviceItem = new DeviceItem(); // SPDRP_DRIVER seems to do a better job at detecting driverless devices than // SPDRP_INSTALL_STATE RegistryValueKind propertyType; int requiredSize; if (SetupApi.SetupDiGetDeviceRegistryProperty(pDevInfo, ref devInfoData, SetupApi.SPDRP.DRIVER, out propertyType, propBuffer, propBuffer.Length, out requiredSize)) { deviceItem.mDriverless = false; // Read all string values from the registry driver key IntPtr hKey = SetupApi.SetupDiOpenDevRegKey(pDevInfo, ref devInfoData, 1, 0, DevKeyType.DRV, (int)RegistryKeyPermissionCheck.ReadSubTree); if (hKey != IntPtr.Zero && hKey != new IntPtr(-1)) { int index = 0; int nameLength = 255; int dataLength = 1023; deviceItem.mDriverRegistryList = new Dictionary <string, object>(); StringBuilder sbName = new StringBuilder(nameLength + 1); StringBuilder sbValue = new StringBuilder(dataLength + 1); RegistryValueKind regValueType; while (SetupApi.RegEnumValue(hKey, index, sbName, ref nameLength, IntPtr.Zero, out regValueType, sbValue, ref dataLength) == 0) { if (regValueType == RegistryValueKind.String) { deviceItem.mDriverRegistryList.Add(sbName.ToString(), sbValue.ToString()); } // Get next key/value index index++; // Reset max lengths nameLength = 255; dataLength = 1023; } SetupApi.RegCloseKey(hKey); } } else { deviceItem.mDriverless = true; } // [trobinson] patch uint status; uint pbmNumber; deviceItem.mIsConnected = (SetupApi.CM_Get_DevNode_Status(out status, out pbmNumber, devInfoData.DevInst, 0) != SetupApi.CR.NO_SUCH_DEVNODE); if (deviceItem.mIsConnected) { deviceItem.mIsConnected = ((pbmNumber & CM_PROB_PHANTOM) != CM_PROB_PHANTOM); } //if (deviceItem.mDriverless && !deviceItem.mIsConnected) // deviceItem.mDriverless = false; // Find only the ones that are driverless if (deviceEnumeratorInfo.DriverlessOnly && !deviceItem.mDriverless) { InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Info, "skipping non driverless device."); continue; } // Driverless devices will return an error InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Info, "driverless device found."); // Eliminate USB hubs by checking the driver string if (!SetupApi.SetupDiGetDeviceRegistryProperty(pDevInfo, ref devInfoData, SetupApi.SPDRP.SERVICE, out propertyType, propBuffer, propBuffer.Length, out requiredSize)) { InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Warning, "failed getting SPDRP.SERVICE"); deviceItem.mServiceName = String.Empty; } else { deviceItem.mServiceName = GetAsAutoString(propBuffer); } bool bContinue = true; foreach (string skipServiceName in mSkipServiceNames) { if (deviceItem.mServiceName.Trim().ToLower() == skipServiceName) { bContinue = false; break; } } if (!bContinue && deviceEnumeratorInfo.SkipWindowsServices) { continue; } //if (!bContinue) // continue; deviceItem.mIsSkipServiceName = !bContinue; string[] saHardwareIDs; // Retrieve the hardware ID if (!SetupApi.SetupDiGetDeviceRegistryProperty(out saHardwareIDs, pDevInfo, ref devInfoData, SetupApi.SPDRP.HARDWAREID)) { InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Win32Error, "failed getting SPDRP.HARDWAREID"); continue; } if (saHardwareIDs.Length == 0) { InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Error, "device does not have any hardware ids"); continue; } for (int hwid = 0; hwid < saHardwareIDs.Length; hwid++) { InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Info, "found hardware ID ({0}/{1}): {2}", hwid + 1, saHardwareIDs.Length, saHardwareIDs[hwid]); } // Get Device ID SetupApi.CR r = SetupApi.CM_Get_Device_ID(devInfoData.DevInst, propBuffer, propBuffer.Length, 0); if (r != SetupApi.CR.SUCCESS) { InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Error, "CM_Get_Device_ID:Failed retrieving simple path for device index: {0} HWID:{1} CR error {2}", devIndex, saHardwareIDs[0], r); continue; } deviceItem.mDeviceId = GetAsAutoString(propBuffer); InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Info, "{0} USB device {1}: {2}", deviceItem.mDriverless ? "Driverless" : deviceItem.mServiceName, devIndex, deviceItem.mDeviceId); string sDeviceDescription; if (SetupApi.WindowsVersion < WindowsVersionType.WINDOWS_7) { // On Vista and earlier, we can use SPDRP_DEVICEDESC bContinue = SetupApi.SetupDiGetDeviceRegistryProperty(out sDeviceDescription, pDevInfo, ref devInfoData, SetupApi.SPDRP.DEVICEDESC); if (!bContinue) { sDeviceDescription = string.Empty; } } else { // On Windows 7, the information we want ("Bus reported device description") is // accessed through DEVPKEY_Device_BusReportedDeviceDesc try { bContinue = SetupApi.SetupDiGetDeviceProperty(pDevInfo, ref devInfoData, SetupApi.DEVPKEY_Device_BusReportedDeviceDesc, out propertyType, propBuffer, propBuffer.Length, out requiredSize, 0); } catch (DllNotFoundException) { //if (SetupDiGetDeviceProperty == NULL) InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Warning, "Failed to locate SetupDiGetDeviceProperty() is Setupapi.dll"); bContinue = false; } if (bContinue) { sDeviceDescription = GetAsAutoString(propBuffer); } else { // fallback to SPDRP_DEVICEDESC (USB husb still use it) bContinue = SetupApi.SetupDiGetDeviceRegistryProperty(out sDeviceDescription, pDevInfo, ref devInfoData, SetupApi.SPDRP.DEVICEDESC); if (!bContinue) { sDeviceDescription = string.Empty; } } } if (!bContinue) { InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Warning | StatusType.Win32Error, "Failed reading read device description for {0}: {1}", devIndex, deviceItem.mDeviceId); } deviceItem.DeviceDescription = sDeviceDescription; deviceItem.BaseFilename = sDeviceDescription; MatchCollection matches = regHardwareID.Matches(saHardwareIDs[0]); foreach (Match match in matches) { foreach (NamedGroup namedGroup in RegHardwareID.NAMED_GROUPS) { RegHardwareID.ENamedGroups groupEnum = (RegHardwareID.ENamedGroups)namedGroup.GroupNumber; Group group = match.Groups[(int)groupEnum]; if (!group.Success) { continue; } switch (groupEnum) { case RegHardwareID.ENamedGroups.Vid: deviceItem.VendorID = group.Value; break; case RegHardwareID.ENamedGroups.Pid: deviceItem.ProductID = group.Value; break; case RegHardwareID.ENamedGroups.Rev: //deviceItem.Rev = group.Value; break; case RegHardwareID.ENamedGroups.MI: deviceItem.MI = group.Value; if (deviceItem.MI != string.Empty) { deviceItem.DeviceDescription += String.Format(" (Interface #{0})", deviceItem.mMI); } break; default: throw new ArgumentOutOfRangeException(); } } } if (deviceItem.mVid == 0 && deviceItem.mPid == 0) { continue; } string sManufacturer; if (!SetupApi.SetupDiGetDeviceRegistryProperty(out sManufacturer, pDevInfo, ref devInfoData, SetupApi.SPDRP.MFG)) { sManufacturer = string.Empty; } deviceItem.Manufacturer = sManufacturer; string[] deviceInterfaceGuids = new string[0]; if (SetupApi.SetupDiGetCustomDeviceProperty(pDevInfo, ref devInfoData, "DeviceInterfaceGUIDs", SetupApi.DICUSTOMDEVPROP.NONE, out propertyType, propBuffer, propBuffer.Length, out requiredSize)) { deviceInterfaceGuids = GetAsAutoStringArray(propBuffer, requiredSize); } if (deviceInterfaceGuids.Length > 0) { deviceItem.DeviceInterfaceGuid = deviceInterfaceGuids[0]; } if (!deviceEnumeratorInfo.DeviceFound(deviceItem, pDevInfo, ref devInfoData)) { break; } InfWizardStatus.Log(CategoryType.EnumerateDevices, StatusType.Info, "device description: {0}", deviceItem.DeviceDescription); } SetupApi.SetupDiDestroyDeviceInfoList(pDevInfo); return(devIndex); }
private static bool BuildMasterCallback(IntPtr deviceInfoSet, int deviceindex, ref SetupApi.SP_DEVINFO_DATA deviceInfoData, object userData) { MasterList deviceList = userData as MasterList; MasterItem deviceItem = new MasterItem(); StringBuilder sb = new StringBuilder(256); if (SetupApi.CM_Get_Device_ID(deviceInfoData.DevInst, sb, sb.Capacity, 0) != SetupApi.CR.SUCCESS) { return(false); } deviceItem.Add(DEVICE_ID_KEY, sb.ToString()); deviceList.Add(deviceItem); RegistryValueKind propertyType; byte[] propBuffer = new byte[256]; int requiredSize; bool bSuccess = SetupApi.SetupDiGetCustomDeviceProperty(deviceInfoSet, ref deviceInfoData, UsbRegistry.DEVICE_INTERFACE_GUIDS, SetupApi.DICUSTOMDEVPROP.NONE, out propertyType, propBuffer, propBuffer.Length, out requiredSize); if (bSuccess) { string[] devInterfaceGuids = UsbRegistry.GetAsStringArray(propBuffer, requiredSize); deviceItem.Add(UsbRegistry.DEVICE_INTERFACE_GUIDS, devInterfaceGuids); foreach (string s in devInterfaceGuids) { Guid g = new Guid(s); List <string> devicePathList; if (WinUsb.WinUsbRegistry.GetDevicePathList(g, out devicePathList)) { deviceItem.DevicePaths.Add(g, devicePathList); } } } else { bSuccess = SetupApi.SetupDiGetCustomDeviceProperty(deviceInfoSet, ref deviceInfoData, UsbRegistry.LIBUSB_INTERFACE_GUIDS, SetupApi.DICUSTOMDEVPROP.NONE, out propertyType, propBuffer, propBuffer.Length, out requiredSize); if (bSuccess) { string[] devInterfaceGuids = UsbRegistry.GetAsStringArray(propBuffer, requiredSize); deviceItem.Add(UsbRegistry.LIBUSB_INTERFACE_GUIDS, devInterfaceGuids); } } bSuccess = SetupApi.SetupDiGetCustomDeviceProperty(deviceInfoSet, ref deviceInfoData, UsbRegistry.SYMBOLIC_NAME_KEY, SetupApi.DICUSTOMDEVPROP.NONE, out propertyType, propBuffer, propBuffer.Length, out requiredSize); if (bSuccess) { string symbolicName = UsbRegistry.GetAsString(propBuffer, requiredSize); deviceItem.Add(UsbRegistry.SYMBOLIC_NAME_KEY, symbolicName); } SetupApi.getSPDRPProperties(deviceInfoSet, ref deviceInfoData, deviceItem); return(false); }
public static UsbDevice FindDriveLetter(string driveName) { UsbDevice foundDevice = null; var instanceID = string.Empty; var devNum = UsbLogic.GetDeviceNumber($@"\\.\{driveName.TrimEnd('\\')}"); if (devNum < default(int)) { return(foundDevice); } var diskGUID = new Guid(UsbConstants.GUID_DEVINTERFACE_DISK); var h = SetupApi.SetupDiGetClassDevs(ref diskGUID, default(int), IntPtr.Zero, UsbConstants.DIGCF_PRESENT | UsbConstants.DIGCF_DEVICEINTERFACE); if (h.ToInt32() != UsbConstants.INVALID_HANDLE_VALUE) { var i = default(int); var success = true; do { var dia = new SpDeviceInterfaceData(); dia.cbSize = Marshal.SizeOf(dia); success = SetupApi.SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref diskGUID, i, ref dia); if (success) { var da = new SpDevinfoData(); da.cbSize = Marshal.SizeOf(da); var didd = new SpDeviceInterfaceDetailData { cbSize = 4 + Marshal.SystemDefaultCharSize, }; var nRequiredSize = default(int); int nBytes = UsbConstants.BUFFER_SIZE; if (SetupApi.SetupDiGetDeviceInterfaceDetail(h, ref dia, ref didd, nBytes, ref nRequiredSize, ref da)) { if (UsbLogic.GetDeviceNumber(didd.DevicePath) == devNum) { SetupApi.CM_Get_Parent(out IntPtr ptrPrevious, da.DevInst, default(int)); var ptrInstanceBuf = Marshal.AllocHGlobal(nBytes); SetupApi.CM_Get_Device_ID(ptrPrevious, ptrInstanceBuf, nBytes, default(int)); instanceID = Marshal.PtrToStringAuto(ptrInstanceBuf); Marshal.FreeHGlobal(ptrInstanceBuf); break; } } } i++; } while (success); SetupApi.SetupDiDestroyDeviceInfoList(h); } if (instanceID.StartsWith("USB\\")) { foundDevice = UsbLogic.FindDeviceByInstanceID(instanceID, driveName); } return(foundDevice); }