public static void Remove(string HardwareId) { IntPtr DeviceInfoSet = SetupDiGetClassDevs(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, (uint)DiGetClassFlags.DIGCF_ALLCLASSES); if (DeviceInfoSet == INVALID_HANDLE_VALUE) { return; } uint index = 0; SP_DEVINFO_DATA DeviceInfoData = new SP_DEVINFO_DATA(); const uint BUFFER_SIZE = 4096; ushort[] buffer = new ushort[BUFFER_SIZE]; DeviceInfoData.cbSize = (uint) Marshal.SizeOf(DeviceInfoData); while (SetupDiEnumDeviceInfo(DeviceInfoSet, index, ref DeviceInfoData)) { index++; SetupDiGetDeviceRegistryProperty(DeviceInfoSet, ref DeviceInfoData, SetupDiGetDeviceRegistryPropertyEnum.SPDRP_HARDWAREID, IntPtr.Zero, buffer, BUFFER_SIZE*2, IntPtr.Zero); int start = 0; int offset = 0; while (start < buffer.Length) { while ((offset < buffer.Length) && (buffer[offset] != 0)) { offset++; } if (offset < buffer.Length) { if (start == offset) break; byte[] block = new byte[(offset - start + 1) * 2]; Buffer.BlockCopy(buffer, (int)(start * 2), block, 0, (int)((offset - start + 1) * 2)); string id = System.Text.Encoding.Unicode.GetString(block, 0, (offset - start) * 2); Trace.WriteLine("Examinining id " + id.ToUpper() +" vs "+HardwareId.ToUpper()); if (id.ToUpper().Equals(HardwareId.ToUpper())) { Trace.WriteLine("Trying to remove "+HardwareId.ToUpper()); REMOVE_PARAMS rparams = new REMOVE_PARAMS(); rparams.cbSize = 8; // Size of cbSide & InstallFunction rparams.InstallFunction = DIF_REMOVE; rparams.HwProfile = 0; rparams.Scope = DI_REMOVE_DEVICE_GLOBAL; GCHandle handle1 = GCHandle.Alloc(rparams); if (!SetupDiSetClassInstallParams(DeviceInfoSet, ref DeviceInfoData, ref rparams, Marshal.SizeOf(rparams))) { throw new Exception("Unable to set class install params"); } if (!SetupDiCallClassInstaller(DIF_REMOVE, DeviceInfoSet, ref DeviceInfoData)) { throw new Exception("Unable to call class installer"); } Trace.WriteLine("Remove should have worked"); } } else { break; } offset++; start = offset; } } }
static extern bool SetupDiSetClassInstallParams(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, ref REMOVE_PARAMS ClassInstallParams, int ClassInstallParamsSize);