public static string[] GetDevRegPropertyMultiStr( SetupApi.DeviceInfoSet devInfoSet, SetupApi.SP_DEVINFO_DATA devInfoData, SetupApi.SPDRP property) // Use this function for any 'Device Registry // Property' that returns 'REG_MULTI_SZ', // e.g. SPDRP_HARDWAREID { int propertyRegDataType; int requiredSize; // 'buffer' is 4KB but Unicode chars are 2 bytes, // hence 'buffer' can hold up to 2K chars const int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; SetupApi.SetupDiGetDeviceRegistryProperty( devInfoSet.Get(), devInfoData, property, out propertyRegDataType, buffer, BUFFER_SIZE, out requiredSize ); return(Helpers.StringArrayFromMultiSz(buffer)); }
public static string GetDevRegPropertyStr( SetupApi.DeviceInfoSet devInfoSet, SetupApi.SP_DEVINFO_DATA devInfoData, SetupApi.SPDRP property) // Use this function for any 'Device Registry // Property' that returns a string, // e.g. SPDRP_CLASSGUID { int propertyRegDataType; int requiredSize; // 'buffer' is 1KB but Unicode chars are 2 bytes, // hence 'buffer' can hold up to 512 chars const int BUFFER_SIZE = 1024; byte[] buffer = new byte[BUFFER_SIZE]; SetupApi.SetupDiGetDeviceRegistryProperty( devInfoSet.Get(), devInfoData, property, out propertyRegDataType, buffer, BUFFER_SIZE, out requiredSize ); return(System.Text.Encoding.Unicode.GetString( buffer, 0, requiredSize )); }
private static IEnumerable <string> EnumerateDevicePath(Guid guid) { var devicePathList = new List <string>(); var hDevInfo = SetupApi.SetupDiGetClassDevs(ref guid, IntPtr.Zero, IntPtr.Zero, SetupApi.DIGCF_PRESENT | SetupApi.DIGCF_DEVICEINTERFACE); var spid = new SetupApi.SP_DEVICE_INTERFACE_DATA(); spid.cbSize = Marshal.SizeOf(spid); int memberindex = 0; while (SetupApi.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, memberindex, ref spid)) { int bufferSize = 0; SetupApi.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref spid, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero); var buffer = Marshal.AllocHGlobal(bufferSize); Marshal.WriteInt32(buffer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8); var da = new SetupApi.SP_DEVINFO_DATA(); da.cbSize = Marshal.SizeOf(da); SetupApi.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref spid, buffer, bufferSize, ref bufferSize, ref da); IntPtr pDevicePathName = new IntPtr(buffer.ToInt64() + 4); string pathName = Marshal.PtrToStringUni(pDevicePathName); Marshal.FreeHGlobal(buffer); buffer = IntPtr.Zero; memberindex++; Console.WriteLine(pathName); devicePathList.Add(pathName); } return(devicePathList); }
public virtual bool DeviceFound(DeviceItem item, IntPtr pDeviceInfoSet, ref SetupApi.SP_DEVINFO_DATA DeviceInfoData) { deviceList.Add(item); return(true); // true to continue enumerating }
public override bool DeviceFound(DeviceItem item, IntPtr pDeviceInfoSet, ref SetupApi.SP_DEVINFO_DATA DeviceInfoData) { if (mRemoveDeviceOptions.RemoveByVidPid) { if (item.VendorID.ToLower() != mRemoveDeviceOptions.DeviceItem.VendorID.ToLower() || item.ProductID.ToLower() != mRemoveDeviceOptions.DeviceItem.ProductID.ToLower()) { return(true); } } else { if (item.mDeviceId != mRemoveDeviceOptions.DeviceItem.mDeviceId) { return(true); } } bool bUninstalled; if (SetupApi.WindowsVersion >= WindowsVersionType.WINDOWS_7) { if ((bUninstalled = SetupApi.DiUninstallDevice(IntPtr.Zero, pDeviceInfoSet, ref DeviceInfoData, 0, IntPtr.Zero)) == true) { mRemoved++; } else { InfWizardStatus.Log(CategoryType.RemoveDevice, StatusType.Warning | StatusType.Win32Error, "failed uninstalling device."); } } else { if ((bUninstalled = SetupApi.SetupDiRemoveDevice(pDeviceInfoSet, ref DeviceInfoData)) == true) { mRemoved++; } else { InfWizardStatus.Log(CategoryType.RemoveDevice, StatusType.Warning | StatusType.Win32Error, "failed uninstalling device."); } } if (bUninstalled) { InfWizardStatus.Log(CategoryType.RemoveDevice, StatusType.Success, "device uninstall complete"); } object oInfFileName; if (item.mDriverRegistryList != null && !item.mIsSkipServiceName) { if (item.mDriverRegistryList.TryGetValue("InfPath", out oInfFileName)) { if (!(SetupApi.SetupUninstallOEMInf(oInfFileName.ToString(), SetupApi.SUOI.FORCEDELETE, IntPtr.Zero))) { InfWizardStatus.Log(CategoryType.RemoveDevice, StatusType.Warning | StatusType.Win32Error, "SetupUninstallOEMInf failed"); } } } return(mRemoveDeviceOptions.RemoveByVidPid); }
/// <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 bool ChildrenInstalled(string enumName) { UInt32 devStatus; UInt32 devProblemCode; SetupApi.SP_DEVINFO_DATA devInfoData = new SetupApi.SP_DEVINFO_DATA(); devInfoData.cbSize = (uint)Marshal.SizeOf(devInfoData); using (SetupApi.DeviceInfoSet devInfoSet = new SetupApi.DeviceInfoSet( IntPtr.Zero, enumName, IntPtr.Zero, SetupApi.DiGetClassFlags.DIGCF_PRESENT | SetupApi.DiGetClassFlags.DIGCF_ALLCLASSES)) { for (uint i = 0; SetupApi.SetupDiEnumDeviceInfo( devInfoSet.Get(), i, devInfoData); ++i) { CfgMgr32.CM_Get_DevNode_Status( out devStatus, out devProblemCode, devInfoData.devInst, 0 ); if ((devStatus & (uint)SetupApi.DNFlags.DN_STARTED) == 0) { Trace.WriteLine( enumName + " child not started " + devStatus.ToString() ); return(false); } } } return(true); }
public static string GetDriverVersion( SetupApi.DeviceInfoSet devInfoSet, SetupApi.SP_DEVINFO_DATA devInfoData) { string driverKeyName = GetDevRegPropertyStr( devInfoSet, devInfoData, SetupApi.SPDRP.DRIVER ); if (String.IsNullOrEmpty(driverKeyName)) { return("0.0.0.0"); } driverKeyName = @"SYSTEM\CurrentControlSet\Control\Class\" + driverKeyName; RegistryKey rk = Registry.LocalMachine.OpenSubKey( driverKeyName, true ); return((string)rk.GetValue("DriverVersion")); }
/* * private static bool WinUsbRegistryCallBack(IntPtr deviceInfoSet, * int deviceIndex, * ref SetupApi.SP_DEVINFO_DATA deviceInfoData, * object classEnumeratorCallbackParam1) * { * * List<WinUsbRegistry> deviceList = (List<WinUsbRegistry>) classEnumeratorCallbackParam1; * * RegistryValueKind propertyType; * byte[] propBuffer = new byte[256]; * int requiredSize; * bool isNew = true; * bool bSuccess; * * bSuccess = SetupApi.SetupDiGetCustomDeviceProperty(deviceInfoSet, * ref deviceInfoData, * DEVICE_INTERFACE_GUIDS, * SetupApi.DICUSTOMDEVPROP.NONE, * out propertyType, * propBuffer, * propBuffer.Length, * out requiredSize); * if (bSuccess) * { * string[] devInterfaceGuids = GetAsStringArray(propBuffer, requiredSize); * * foreach (String devInterfaceGuid in devInterfaceGuids) * { * Guid g = new Guid(devInterfaceGuid); * List<string> devicePaths; * if (SetupApi.GetDevicePathList(g, out devicePaths)) * { * foreach (string devicePath in devicePaths) * { * WinUsbRegistry regInfo = new WinUsbRegistry(); * * SetupApi.getSPDRPProperties(deviceInfoSet, ref deviceInfoData, 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, devicePath); * * regInfo.mDeviceInterfaceGuids = new Guid[] { g }; * * // Don't add duplicate devices (with the same device path) * WinUsbRegistry foundRegistry=null; * foreach (WinUsbRegistry usbRegistry in deviceList) * { * if (usbRegistry.SymbolicName == regInfo.SymbolicName) * { * foundRegistry = usbRegistry; * break; * } * } * if (foundRegistry == null) * deviceList.Add(regInfo); * else * { * if (isNew) * { * deviceList.Remove(foundRegistry); * deviceList.Add(regInfo); * } * else * { * * // If the device path already exists, add this compatible guid * // to the foundRegstry guid list. * List<Guid> newGuidList = new List<Guid>(foundRegistry.mDeviceInterfaceGuids); * if (!newGuidList.Contains(g)) * { * newGuidList.Add(g); * foundRegistry.mDeviceInterfaceGuids = newGuidList.ToArray(); * } * } * } * isNew = false; * } * } * } * } * * return false; * } */ private static bool WinUsbRegistryCallBack(IntPtr deviceInfoSet, int deviceIndex, ref SetupApi.SP_DEVINFO_DATA deviceInfoData, object classEnumeratorCallbackParam1) { List <WinUsbRegistry> deviceList = (List <WinUsbRegistry>)classEnumeratorCallbackParam1; RegistryValueKind propertyType; byte[] propBuffer = new byte[256]; int requiredSize; bool bSuccess; bSuccess = SetupApi.SetupDiGetCustomDeviceProperty(deviceInfoSet, ref deviceInfoData, DEVICE_INTERFACE_GUIDS, SetupApi.DICUSTOMDEVPROP.NONE, out propertyType, propBuffer, propBuffer.Length, out requiredSize); if (bSuccess) { string[] devInterfaceGuids = GetAsStringArray(propBuffer, requiredSize); foreach (String devInterfaceGuid in devInterfaceGuids) { Guid g = new Guid(devInterfaceGuid); List <WinUsbRegistry> tempList; if (GetWinUsbRegistryList(g, out tempList)) { foreach (WinUsbRegistry regInfo in tempList) { // Don't add duplicate devices (with the same device path) WinUsbRegistry foundRegistry = null; foreach (WinUsbRegistry usbRegistry in deviceList) { if (usbRegistry.SymbolicName == regInfo.SymbolicName) { foundRegistry = usbRegistry; break; } } if (foundRegistry == null) { deviceList.Add(regInfo); } else { // If the device path already exists, add this compatible guid // to the foundRegstry guid list. List <Guid> newGuidList = new List <Guid>(foundRegistry.mDeviceInterfaceGuids); if (!newGuidList.Contains(g)) { newGuidList.Add(g); foundRegistry.mDeviceInterfaceGuids = newGuidList.ToArray(); } } } } } } return(false); }
public static SetupApi.SP_DEVINFO_DATA FindInSystem( string hwID, SetupApi.DeviceInfoSet devInfoSet, bool strictSearch) // The function takes as input an initialized 'deviceInfoSet' // object and a hardware ID string we want to search the system // for. If 'strictSearch' is true, the device needs to exactly // match the hwID to be returned. Otherwise, the device's name // needs to start with the supplied hwID string. If the device // is found, a fully initialized 'SP_DEVINFO_DATA' object is // returned. If not, the function returns 'null'. { SetupApi.SP_DEVINFO_DATA devInfoData = new SetupApi.SP_DEVINFO_DATA(); devInfoData.cbSize = (uint)Marshal.SizeOf(devInfoData); // Select which string comparison function // to use, depending on 'strictSearch' Func <string, string, bool> hwIDFound; if (strictSearch) { hwIDFound = (string _enumID, string _hwID) => _enumID.Equals( _hwID, StringComparison.OrdinalIgnoreCase ); } else { hwIDFound = (string _enumID, string _hwID) => _enumID.StartsWith( _hwID, StringComparison.OrdinalIgnoreCase ); } Trace.WriteLine( "Searching system for device: \'" + hwID + "\'; (strict search: \'" + strictSearch + "\')" ); for (uint i = 0; SetupApi.SetupDiEnumDeviceInfo( devInfoSet.Get(), i, devInfoData); ++i) { string [] ids = GetDevRegPropertyMultiStr( devInfoSet, devInfoData, SetupApi.SPDRP.HARDWAREID ); foreach (string id in ids) { if (hwIDFound(id, hwID)) { Trace.WriteLine( "Found: \'" + String.Join(" ", ids) + "\'" ); return(devInfoData); } } } Win32Error.Set("SetupDiEnumDeviceInfo"); if (Win32Error.GetErrorNo() == WinError.ERROR_NO_MORE_ITEMS) { Trace.WriteLine("Device not found"); return(null); } throw new Exception(Win32Error.GetFullErrMsg()); }
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); }
private static void SetPVToolsVersionOnFirstRun( RegistryKey openRegKey) { string regValName = "PVToolsVersionOnFirstRun"; int tmp = (int)openRegKey.GetValue(regValName, -1); string drvVer; if (tmp != -1) { // We can save some indentation.. goto SetStaticVariable; } if (xenBusDev == (XenBus.Devs) 0) { tmp = 0; // None drvVer = "0.0.0.0"; } else { using (SetupApi.DeviceInfoSet devInfoSet = new SetupApi.DeviceInfoSet( IntPtr.Zero, "PCI", IntPtr.Zero, SetupApi.DiGetClassFlags.DIGCF_ALLCLASSES | SetupApi.DiGetClassFlags.DIGCF_PRESENT)) { int idx = Helpers.BitIdxFromFlag((uint)xenBusDev); SetupApi.SP_DEVINFO_DATA devInfoData = Device.FindInSystem( XenBus.hwIDs[idx], devInfoSet, true ); drvVer = Device.GetDriverVersion( devInfoSet, devInfoData ); } // Split the DriverVersion string on the '.' // char and parse the 1st substring (major // version number) tmp = Int32.Parse( drvVer.Split(new char[] { '.' })[0] ); if (tmp != 8) // Eight { tmp = 7; // LessThanEight } } Trace.WriteLine( "XenBus driver version on first run: \'" + drvVer + "\'" ); openRegKey.SetValue( regValName, tmp, RegistryValueKind.DWord ); SetStaticVariable: pvToolsVer = (PVToolsVersion)Enum.Parse( typeof(PVToolsVersion), tmp.ToString() ); }
/// <summary> /// Force re-enumeration of a device (force installation) /// TODO: allow root re-enum /// </summary> public static int UpdateDriver(string deviceHardwareID) { int devIndex; int refreshed = 0; bool bSuccess; // Initialize the SP_DEVINFO_DATA structure SetupApi.SP_DEVINFO_DATA devInfoData = new SetupApi.SP_DEVINFO_DATA(); // List all connected USB devices IntPtr pDevInfo = SetupApi.SetupDiGetClassDevs(0, "USB", IntPtr.Zero, SetupApi.DICFG.ALLCLASSES); if (pDevInfo == IntPtr.Zero || pDevInfo == new IntPtr(-1)) { return(refreshed); } for (devIndex = 0;; devIndex++) { devInfoData.cbSize = (uint)Marshal.SizeOf(typeof(SetupApi.SP_DEVINFO_DATA)); bSuccess = SetupApi.SetupDiEnumDeviceInfo(pDevInfo, devIndex, ref devInfoData); // Reached the end of the deviceInfo list. if (!bSuccess) { break; } // Find the hardware ID string[] saHardwareIDs; bSuccess = SetupApi.SetupDiGetDeviceRegistryProperty(out saHardwareIDs, pDevInfo, ref devInfoData, SetupApi.SPDRP.HARDWAREID); // Failed getting hardware id if (!bSuccess) { break; } // Failed getting hardware id if (saHardwareIDs.Length == 0) { continue; } // Check all hardwareids for a match bool bFound = false; foreach (string s in saHardwareIDs) { if (s.Trim().ToLower() == deviceHardwareID.Trim().ToLower()) { bFound = true; break; } } // Hardware did not match; goto next device if (!bFound) { continue; } // Re-enumerate the device node SetupApi.CR status = SetupApi.CM_Reenumerate_DevNode((int)devInfoData.DevInst, SetupApi.CM.REENUMERATE_RETRY_INSTALLATION); if (status == SetupApi.CR.SUCCESS) { InfWizardStatus.Log(CategoryType.RefreshDriver, StatusType.Success, "re-enumeration of {0} succeeded...", deviceHardwareID); } else if (status == SetupApi.CR.INVALID_DEVNODE) { continue; } else { InfWizardStatus.Log(CategoryType.RefreshDriver, StatusType.Warning, "failed to re-enumerate device node: CR code {0}", status); continue; } refreshed++; } // return the number of devices that were re-enumerated. return(refreshed); }
/// <summary> /// Flag phantom/removed devices for reinstallation. /// See: http://msdn.microsoft.com/en-us/library/aa906206.aspx /// </summary> public static int CheckRemoved(string deviceHardwareID) { int devIndex; int removed = 0; bool bSuccess; // 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)); // List all connected USB devices IntPtr pDevInfo = SetupApi.SetupDiGetClassDevs(0, "USB", IntPtr.Zero, SetupApi.DICFG.ALLCLASSES); if (pDevInfo == IntPtr.Zero || pDevInfo == new IntPtr(-1)) { return(removed); } for (devIndex = 0;; devIndex++) { bSuccess = SetupApi.SetupDiEnumDeviceInfo(pDevInfo, devIndex, ref devInfoData); // Reached the end of the deviceInfo list. if (!bSuccess) { break; } // Find the hardware ID string[] saHardwareIDs; bSuccess = SetupApi.SetupDiGetDeviceRegistryProperty(out saHardwareIDs, pDevInfo, ref devInfoData, SetupApi.SPDRP.HARDWAREID); // Failed getting hardware id if (!bSuccess) { break; } // Failed getting hardware id if (saHardwareIDs.Length == 0) { continue; } // Check all hardwareids for a match bool bFound = false; foreach (string s in saHardwareIDs) { if (s.Trim().ToLower() == deviceHardwareID.Trim().ToLower()) { bFound = true; break; } } // Hardware did not match; goto next device if (!bFound) { continue; } uint status; uint pbmNumber; // If not Unplugged. bSuccess = (SetupApi.CM_Get_DevNode_Status(out status, out pbmNumber, devInfoData.DevInst, 0) == SetupApi.CR.NO_SUCH_DEVNODE); if (!bSuccess) { continue; } // Flag for reinstall on next plugin uint configFlags; bSuccess = SetupApi.SetupDiGetDeviceRegistryProperty(out configFlags, pDevInfo, ref devInfoData, SetupApi.SPDRP.CONFIGFLAGS); if (!bSuccess) { InfWizardStatus.Log(CategoryType.CheckRemoved, StatusType.Warning, "could not read SPDRP_CONFIGFLAGS for phantom device {0}", deviceHardwareID); continue; } // Mark for re-installation configFlags |= (uint)SetupApi.CONFIGFLAG.REINSTALL; uint[] flags = new uint[] { configFlags }; bSuccess = SetupApi.SetupDiSetDeviceRegistryProperty(pDevInfo, ref devInfoData, SetupApi.SPDRP.CONFIGFLAGS, flags, Marshal.SizeOf(typeof(uint))); if (!bSuccess) { InfWizardStatus.Log(CategoryType.CheckRemoved, StatusType.Warning, "could not write SPDRP_CONFIGFLAGS for phantom device {0}", deviceHardwareID); continue; } removed++; } if (removed > 0) { InfWizardStatus.Log(CategoryType.CheckRemoved, StatusType.Info, "flagged {0} removed devices for reinstallation", removed); } SetupApi.SetupDiDestroyDeviceInfoList(pDevInfo); return(removed); }
private static void VifDisableEnable(bool enable) { string action = enable ? "enable" : "disable"; Trace.WriteLine("===> VifDisableEnable: \'" + action + "\'"); using (SetupApi.DeviceInfoSet devInfoSet = new SetupApi.DeviceInfoSet( IntPtr.Zero, "XENVIF", IntPtr.Zero, SetupApi.DiGetClassFlags.DIGCF_PRESENT | SetupApi.DiGetClassFlags.DIGCF_ALLCLASSES)) { SetupApi.SP_DEVINFO_DATA devInfoData = new SetupApi.SP_DEVINFO_DATA(); devInfoData.cbSize = (uint)Marshal.SizeOf(devInfoData); for (uint i = 0; SetupApi.SetupDiEnumDeviceInfo( devInfoSet.Get(), i, devInfoData); ++i) { SetupApi.PropertyChangeParameters pcParams = new SetupApi.PropertyChangeParameters(); pcParams.size = 8; pcParams.diFunction = SetupApi.DI_FUNCTION.DIF_PROPERTYCHANGE; pcParams.scope = SetupApi.Scopes.Global; if (enable) { pcParams.stateChange = SetupApi.StateChangeAction.Enable; } else { pcParams.stateChange = SetupApi.StateChangeAction.Disable; } pcParams.hwProfile = 0; var pinned = GCHandle.Alloc(pcParams, GCHandleType.Pinned); byte[] temp = new byte[Marshal.SizeOf(pcParams)]; Marshal.Copy( pinned.AddrOfPinnedObject(), temp, 0, Marshal.SizeOf(pcParams) ); var pdd = GCHandle.Alloc(devInfoData, GCHandleType.Pinned); if (!SetupApi.SetupDiSetClassInstallParams( devInfoSet.Get(), pdd.AddrOfPinnedObject(), pinned.AddrOfPinnedObject(), Marshal.SizeOf(pcParams))) { Win32Error.Set("SetupDiSetClassInstallParams"); Trace.WriteLine(Win32Error.GetFullErrMsg()); } if (!SetupApi.SetupDiCallClassInstaller( SetupApi.DI_FUNCTION.DIF_PROPERTYCHANGE, devInfoSet.Get(), pdd.AddrOfPinnedObject())) { Win32Error.Set("SetupDiCallClassInstaller"); Trace.WriteLine(Win32Error.GetFullErrMsg()); } pdd.Free(); pinned.Free(); } } Trace.WriteLine("<=== VifDisableEnable"); }