MainWindow.xaml.cs (7112B)
1 using System.Collections.ObjectModel; 2 using System.ComponentModel; 3 using System.Diagnostics; 4 using System.Windows; 5 using System.Windows.Navigation; 6 7 namespace DriverUpdater; 8 9 public partial class MainWindow : Window 10 { 11 // Each check returns rows for the devices it covers, or none when that hardware isn't present. 12 static readonly (string Name, Func<IReadOnlyList<InstalledDevice>, Task<List<DriverUpdate>>> Run)[] Checks = 13 [ 14 ("Windows Update", installed => Task.Run(() => WindowsUpdate.Search(installed))), 15 ("NVIDIA", Nvidia.CheckAsync), 16 ("AMD graphics", Amd.CheckGraphicsAsync), 17 ("AMD chipset", Amd.CheckChipsetAsync), 18 ("Intel", Intel.CheckAsync), 19 ]; 20 21 readonly ObservableCollection<DriverUpdate> rows = []; 22 bool busy; 23 24 public MainWindow() 25 { 26 InitializeComponent(); 27 UpdatesGrid.ItemsSource = rows; 28 Loaded += async (_, _) => await ScanAsync(); 29 } 30 31 async void Scan_Click(object sender, RoutedEventArgs e) => await ScanAsync(); 32 33 async void Install_Click(object sender, RoutedEventArgs e) 34 { 35 var chosen = rows.Where(row => row.IsSelected && row.CanInstall).ToList(); 36 SetBusy(true); 37 38 if (RestorePointBox.IsChecked == true && !await CreateRestorePointAsync()) 39 { 40 StatusText.Text = "Nothing installed"; 41 SetBusy(false); 42 return; 43 } 44 45 bool restartNeeded = false; 46 foreach (var update in chosen) 47 { 48 StatusText.Text = $"Updating {update.Device}"; 49 try 50 { 51 restartNeeded |= await InstallAsync(update); 52 update.IsSelected = false; 53 } 54 catch (Exception ex) 55 { 56 update.Status = $"Failed: {ex.Message}"; 57 } 58 } 59 60 StatusText.Text = "Cleaning up"; 61 await DeleteTemporaryPackagesAsync(chosen); 62 StatusText.Text = restartNeeded ? "Done. Restart Windows to finish." : "Done"; 63 SetBusy(false); 64 } 65 66 async Task ScanAsync() 67 { 68 SetBusy(true); 69 rows.Clear(); 70 StatusText.Text = "Reading installed drivers"; 71 List<InstalledDevice> installed; 72 try 73 { 74 installed = await Task.Run(InstalledDevices.Read); 75 } 76 catch (Exception ex) 77 { 78 // Every check needs the device list, so there's nothing to do without it. 79 StatusText.Text = $"Couldn't read installed drivers from WMI: {ex.Message}"; 80 SetBusy(false); 81 return; 82 } 83 84 StatusText.Text = "Checking Windows Update, NVIDIA, AMD, and Intel"; 85 var results = await Task.WhenAll(Checks.Select(check => RunCheckAsync(check.Name, check.Run, installed))); 86 foreach (var row in results.SelectMany(rowsFromOneCheck => rowsFromOneCheck)) 87 { 88 row.PropertyChanged += Row_PropertyChanged; 89 rows.Add(row); 90 } 91 92 int available = rows.Count(row => row.CanInstall); 93 StatusText.Text = available == 0 ? "No updates found" : $"{available} updates available"; 94 SetBusy(false); 95 } 96 97 // A failed check becomes a row of its own, so one vendor being down doesn't hide the others. 98 static async Task<List<DriverUpdate>> RunCheckAsync( 99 string name, 100 Func<IReadOnlyList<InstalledDevice>, Task<List<DriverUpdate>>> run, 101 IReadOnlyList<InstalledDevice> installed) 102 { 103 try 104 { 105 return await run(installed); 106 } 107 catch (Exception ex) 108 { 109 return [new DriverUpdate { Device = $"{name} check", Source = name, Status = $"Failed: {ex.Message}" }]; 110 } 111 } 112 113 // Returns true if Windows needs a restart to finish. 114 static async Task<bool> InstallAsync(DriverUpdate update) 115 { 116 if (update.WindowsUpdateItem is { } item) 117 { 118 update.Status = "Downloading"; 119 await Task.Run(() => WindowsUpdate.Download(item)); 120 update.Status = "Installing"; 121 bool restartNeeded = await Task.Run(() => WindowsUpdate.Install(item)); 122 update.Status = restartNeeded ? "Installed. Restart needed" : "Installed"; 123 return restartNeeded; 124 } 125 126 // A vendor driver. Unpack the vendor's package and install only the INF for this device. 127 string folder = await update.Package!.UnpackAsync(status => update.Status = status); 128 update.Status = "Finding the driver"; 129 var inf = await Task.Run(() => InfFiles.Load(folder).FindFor(update.TargetDevice!)) 130 ?? throw new InvalidOperationException("Nothing in the package matches this device"); 131 132 update.Status = "Installing"; 133 var result = await Task.Run(() => PnpDriver.Install(inf)); 134 update.Status = result switch 135 { 136 DriverInstallResult.Installed => "Installed", 137 DriverInstallResult.RestartNeeded => "Installed. Restart needed", 138 _ => "Windows kept the current driver", 139 }; 140 return result == DriverInstallResult.RestartNeeded; 141 } 142 143 // Graphics packages unpack to several GB, so they go once every row that needs them is done. 144 static Task DeleteTemporaryPackagesAsync(IEnumerable<DriverUpdate> installed) => 145 Task.Run(() => 146 { 147 var packages = installed.Select(row => row.Package).OfType<VendorPackage>().Distinct(); 148 foreach (var package in packages.Where(package => !package.KeepAfterInstall)) 149 package.Delete(); 150 }); 151 152 // Returns false if the restore point failed and the user chose not to go on without one. 153 async Task<bool> CreateRestorePointAsync() 154 { 155 StatusText.Text = "Creating a restore point"; 156 string? error; 157 try 158 { 159 error = await Task.Run(() => RestorePoint.Create("Before driver updates")); 160 } 161 catch (Exception ex) 162 { 163 error = ex.Message; 164 } 165 if (error is null) 166 return true; 167 168 var answer = MessageBox.Show(this, 169 $"Couldn't create a restore point: {error}\n\nInstall anyway?", 170 Title, MessageBoxButton.YesNo, MessageBoxImage.Warning); 171 return answer == MessageBoxResult.Yes; 172 } 173 174 // This app runs as admin, and a browser started from it would run as admin too. Explorer hands the 175 // link to the user's normal desktop session instead. 176 void Link_RequestNavigate(object sender, RequestNavigateEventArgs e) 177 { 178 Process.Start("explorer.exe", e.Uri.AbsoluteUri); 179 e.Handled = true; 180 } 181 182 void Row_PropertyChanged(object? sender, PropertyChangedEventArgs e) 183 { 184 if (e.PropertyName == nameof(DriverUpdate.IsSelected)) 185 UpdateInstallButton(); 186 } 187 188 void SetBusy(bool value) 189 { 190 busy = value; 191 ScanButton.IsEnabled = !busy; 192 BusyBar.Visibility = busy ? Visibility.Visible : Visibility.Collapsed; 193 UpdateInstallButton(); 194 } 195 196 void UpdateInstallButton() => InstallButton.IsEnabled = !busy && rows.Any(row => row.IsSelected); 197 }