public static extern bool SetupDiSetClassInstallParams(SafeDeviceInfoSetHandle deviceInfoSet, [In] ref DeviceInfoData deviceInfoData, [In] ref PropertyChangeParameters classInstallParams, int classInstallParamsSize);
public static extern bool SetupDiEnumDeviceInfo(SafeDeviceInfoSetHandle deviceInfoSet, int memberIndex, ref DeviceInfoData deviceInfoData);
public static extern bool SetupDiCallClassInstaller(DiFunction installFunction, SafeDeviceInfoSetHandle deviceInfoSet, [In] ref DeviceInfoData deviceInfoData);
// Find the index of the particular DeviceInfoData for the instanceId. private static int GetIndexOfInstance(SafeDeviceInfoSetHandle handle, DeviceInfoData[] diData, string instanceId) { for (int index = 0; index < diData.Length; index++) { if (GetInstanceMatch(handle, diData[index], instanceId)) return index; } // not found return -1; }
private static DeviceInfoData[] GetDeviceInfoData(SafeDeviceInfoSetHandle handle) { List<DeviceInfoData> data = new List<DeviceInfoData>(); DeviceInfoData did = new DeviceInfoData(); int index = 0; int didSize = Marshal.SizeOf(did); did.Size = didSize; while (NativeMethods.SetupDiEnumDeviceInfo(handle, index, ref did)) { data.Add(did); index += 1; did = new DeviceInfoData { Size = didSize }; } return data.ToArray(); }
// enable/disable... private static void EnableDevice(SafeDeviceInfoSetHandle handle, DeviceInfoData diData, bool enable) { PropertyChangeParameters parameters = new PropertyChangeParameters { Size = 8, DiFunction = DiFunction.PropertyChange, Scope = Scopes.Global, StateChange = enable ? StateChangeAction.Enable : StateChangeAction.Disable }; // The size is just the size of the header, but we've flattened the structure. // The header comprises the first two fields, both integer. bool result = NativeMethods.SetupDiSetClassInstallParams(handle, ref diData, ref parameters, Marshal.SizeOf(parameters)); if (result == false) throw new Win32Exception(); result = NativeMethods.SetupDiCallClassInstaller(DiFunction.PropertyChange, handle, ref diData); if (result) { return; } int err = Marshal.GetLastWin32Error(); if (err == (int)SetupApiError.NotDisableable) throw new ArgumentException("Device can't be disabled (programmatically or in Device Manager)."); if (err >= (int)SetupApiError.NoAssociatedClass && err <= (int)SetupApiError.OnlyValidateViaAuthenticode) throw new Win32Exception("SetupAPI error: " + ((SetupApiError)err)); throw new Win32Exception(); }