PnpDriver.cs (1771B)
1 using System.ComponentModel; 2 using System.Runtime.InteropServices; 3 4 namespace DriverUpdater; 5 6 enum DriverInstallResult { Installed, RestartNeeded, NotNewer } 7 8 // Installs a driver INF on the devices it matches, the same way Device Manager's "Update driver" does. 9 // Windows replaces the current driver only if the new one ranks higher, so this never downgrades. The 10 // driver store checks the package's signature before it takes the driver. 11 static class PnpDriver 12 { 13 // Fail instead of showing a dialog. 14 const uint InstallFlagNonInteractive = 0x4; 15 16 // The INF matched, but Windows ranks the current driver as good or better. 17 const int ErrorNoMoreItems = 259; 18 19 // SetupAPI's ERROR_NO_SUCH_DEVINST: no device on this PC has the ID. 20 const int ErrorNoSuchDevice = unchecked((int)0xE000020B); 21 22 public static DriverInstallResult Install(DriverInf inf) 23 { 24 if (UpdateDriverForPlugAndPlayDevicesW(IntPtr.Zero, inf.HardwareId, inf.Path, InstallFlagNonInteractive, out bool restartNeeded)) 25 return restartNeeded ? DriverInstallResult.RestartNeeded : DriverInstallResult.Installed; 26 27 int error = Marshal.GetLastWin32Error(); 28 return error switch 29 { 30 ErrorNoMoreItems => DriverInstallResult.NotNewer, 31 ErrorNoSuchDevice => throw new InvalidOperationException($"No device here has the ID {inf.HardwareId}"), 32 _ => throw new Win32Exception(error, $"{new Win32Exception(error).Message} (0x{error:X8})"), 33 }; 34 } 35 36 [DllImport("newdev.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] 37 static extern bool UpdateDriverForPlugAndPlayDevicesW( 38 IntPtr parentWindow, string hardwareId, string infPath, uint flags, out bool restartNeeded); 39 }