### Implement IOptimization for a Custom System Tweak Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Example of a minimal custom optimization implementation. It registers a registry value and automatically captures its revert step. Ensure the Optimization attribute is correctly set. ```csharp // Minimal custom optimization implementation [Optimization( Id = "A1B2C3D4-0000-0000-0000-000000000001", Risk = OptimizationRisk.Safe, Tags = OptimizationTags.Performance | OptimizationTags.System )] public class MyOptimization : BaseOptimization { public override Task ApplyAsync( IProgress progress, OptimizationContext context) { progress.Report(new ProcessingProgress { Message = "Applying tweak...", IsIndeterminate = true }); // Write a registry value; the revert step is recorded automatically RegistryService.Write( new RegistryItem( @"HKLM\SYSTEM\CurrentControlSet\Control\PriorityControl", "Win32PrioritySeparation", 38, RegistryValueKind.DWord ) ); context.Logger.LogInformation("MyOptimization applied successfully"); return Task.FromResult(ApplyResult.True()); // On failure: // return Task.FromResult(ApplyResult.False("Reason why it failed")); } } ``` -------------------------------- ### Implement IOptimizationCategory with Nested Optimizations Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Example of an optimization category grouping related optimizations. Nested classes implementing IOptimization are automatically discovered. This example disables background apps via registry edits. ```csharp [OptimizationCategory(typeof(PerformanceOptimizerPage))] public class Performance : IOptimizationCategory { public string Name => Loc.Instance[$"Optimizer.{nameof(Performance)}"]; public OptimizationCategoryOrder Order { get; init; } = OptimizationCategoryOrder.Performance; public ObservableCollection Optimizations { get; init; } = []; // Each nested class becomes one optimization entry in the UI [Optimization(Id = "648EC19A-FDA5-4607-8A7C-148B8B05FB4C", Risk = OptimizationRisk.Moderate, Tags = OptimizationTags.System | OptimizationTags.Performance | OptimizationTags.Ram)] public class DisableBackgroundApps : BaseOptimization { public override Task ApplyAsync( IProgress progress, OptimizationContext context) { RegistryService.Write( new RegistryItem( @"HKCU\Software\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications", "GlobalUserDisabled", 1), new RegistryItem( @"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Search", "BackgroundAppGlobalToggle", 0) ); return Task.FromResult(ApplyResult.True()); } } } ``` -------------------------------- ### IRevertStep - Serializable Undo Unit Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Illustrates the use of IRevertStep for creating serializable undo units. It shows examples of RegistryRevertStep for managing registry values and ShellRevertStep for undoing shell command changes, including serialization to JSON and execution. ```APIDOC ## RegistryRevertStep ### Description Restores or deletes a registry value as part of an undo operation. The step captures the original value for restoration and can be serialized to JSON for persistence. ### Properties - `Action` (RevertAction): The action to perform (e.g., `RestorePrevious`). - `Path` (string): The registry path. - `Name` (string): The name of the registry value. - `Value` (object): The original value to restore. - `Kind` (RegistryValueKind): The type of the registry value. ### Usage Example ```csharp var revertStep = new RegistryRevertStep { Action = RevertAction.RestorePrevious, Path = @"HKLM\SYSTEM\CurrentControlSet\Control\PriorityControl", Name = "Win32PrioritySeparation", Value = 2, // original value captured before the write Kind = RegistryValueKind.DWord, }; // Serialized to JSON for persistence: JObject json = revertStep.ToData(); bool success = await revertStep.ExecuteAsync(); // restores the original value ``` ## ShellRevertStep ### Description Re-runs a command to undo a shell-based change. This is useful for reverting operations performed via shell commands. ### Properties - `ShellType` (ShellType): The type of shell to use (e.g., `PowerShell`). - `Command` (string): The shell command to execute for undoing the change. ### Usage Example ```csharp var shellRevert = new ShellRevertStep { ShellType = ShellType.PowerShell, Command = "Set-ItemProperty -Path 'HKLM:\...' -Name 'Key' -Value 0" }; await shellRevert.ExecuteAsync(); ``` ``` -------------------------------- ### Discover and Load Optimizations with OptimizationRegistry Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Uses reflection to find and instantiate all `IOptimizationCategory` and `IOptimization` implementations. Call `PreloadOptimizations` once at startup to populate the registry. ```csharp // Called once at startup var registry = new OptimizationRegistry(loggerFactory); await registry.PreloadOptimizations(); // Logs: "Total 6 categories and 35 optimizations found" ``` ```csharp // Access all categories (ordered by OptimizationCategoryOrder) foreach (var category in registry.OptimizationCategories) { Console.WriteLine($"Category: {category.Name} ({category.Optimizations.Count} items)"); foreach (var opt in category.Optimizations) { Console.WriteLine($" [{opt.Risk}] {opt.Name} — applied: {opt.State.IsApplied}"); } } ``` ```csharp // Get a specific category by type var perfCategory = registry.GetCategory(typeof(Performance)); ``` -------------------------------- ### IFeature - Binary Toggle for Windows Features Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Demonstrates how to use the IFeature interface for binary toggles, specifically the Desktop feature which controls the visibility of 'This PC' on the desktop. It shows programmatic usage for checking state, enabling, and disabling the feature, including restarting Explorer. ```APIDOC ## Desktop.ShowThisPc ### Description This feature toggle controls the visibility of the 'This PC' icon on the desktop. Enabling it shows the icon, and disabling it hides the icon. This operation requires restarting Windows Explorer to take effect. ### Method - `GetStateAsync()`: Retrieves the current state of the feature. - `EnableAsync()`: Enables the feature, showing the 'This PC' icon and restarting Explorer. - `DisableAsync()`: Disables the feature, hiding the 'This PC' icon and restarting Explorer. ### Usage Example ```csharp IFeature feature = new Desktop.ShowThisPc(); bool isEnabled = await feature.GetStateAsync(); // true if icon is visible await feature.EnableAsync(); // shows "This PC" on desktop, restarts Explorer await feature.DisableAsync(); // hides "This PC", restarts Explorer ``` ``` -------------------------------- ### Build Project for CI Source: https://github.com/itsfatduck/optimizerduck/blob/master/AGENTS.md Build the project with the configuration typically used in CI environments. The --no-restore flag assumes dependencies have already been restored. ```bash dotnet build optimizerDuck.slnx --configuration Release --no-restore ``` -------------------------------- ### Run Project Locally Source: https://github.com/itsfatduck/optimizerduck/blob/master/AGENTS.md Command to run the application locally for development and testing purposes. ```bash dotnet run --project optimizerDuck/optimizerDuck.csproj ``` -------------------------------- ### Manage Application Settings with ConfigManager Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Reads and writes `appsettings.json` using strongly typed expressions against `AppSettings`. Initialize on startup and use `SetAsync` to modify settings. ```csharp // Initialize on app startup await configManager.InitializeAsync(); await configManager.EnsureDefaultsAsync(); // fills in missing keys with defaults ``` ```csharp // Read via IOptions (injected) string lang = appSettings.Value.App.Language; // "en-US" ApplicationTheme theme = appSettings.Value.App.Theme; // Dark ``` ```csharp // Write using strongly typed expression await configManager.SetAsync(x => x.App.Language, "vi-VN"); await configManager.SetAsync(x => x.App.Theme, ApplicationTheme.Light); await configManager.SetAsync(x => x.Optimize.ShellTimeoutMs, 60000); await configManager.SetAsync(x => x.Optimize.ShowCompletionNotification, true); await configManager.SetAsync(x => x.Bloatware.RemoveProvisioned, false); ``` ```csharp // Write by key string await configManager.SetAsync("App:Language", "zh-TW"); ``` ```csharp // Remove a key await configManager.RemoveAsync("App:Language"); ``` ```csharp // Default AppSettings values: // App.Language = "en-US" // App.Theme = ApplicationTheme.Dark // App.LegalAccepted = false // Optimize.ShellTimeoutMs = 120000 (2 minutes) // Optimize.ShowCompletionNotification = false // Bloatware.RemoveProvisioned = true ``` ```csharp // Static validation (safe to call before DI is ready) ConfigManager.ValidateConfig(); // resets appsettings.json if corrupt or missing ``` -------------------------------- ### Restore Dependencies Source: https://github.com/itsfatduck/optimizerduck/blob/master/AGENTS.md Use this command to restore project dependencies before building or running. ```bash dotnet restore optimizerDuck.slnx ``` -------------------------------- ### Orchestrate Optimization Application and Reversion Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Applies optimizations, reports progress, and handles reversion. Includes functionality to check if an optimization is applied, update states, and retry failed steps. Can create a Windows restore point before changes. ```csharp // Apply an optimization (injected via DI) OptimizationResult result = await optimizationService.ApplyAsync( optimization, new Progress(p => { Console.WriteLine($"[{p.Value}/{p.Total}] {p.Message}"); }) ); switch (result.Status) { case OptimizationSuccessResult.Success: Console.WriteLine($"Done: {result.Message}"); break; case OptimizationSuccessResult.PartialSuccess: Console.WriteLine($"Partial: {result.FailedSteps.Count} step(s) failed"); foreach (var step in result.FailedSteps) Console.WriteLine($" - {step.Name}: {step.Error}"); break; case OptimizationSuccessResult.Failed: Console.WriteLine($"Failed: {result.Message}"); Console.WriteLine(result.Exception?.ToString()); break; } // Revert an applied optimization RevertResult revertResult = await optimizationService.RevertAsync(optimization); Console.WriteLine(revertResult.Success ? "Reverted" : revertResult.Message); // Check if an optimization is already applied bool isApplied = await OptimizationService.IsAppliedAsync(optimization.Id); // Refresh applied/unapplied state for a list of optimizations await OptimizationService.UpdateOptimizationStateAsync(allOptimizations); // optimization.State.IsApplied and optimization.State.AppliedAt are now populated // Retry specific failed steps (e.g., after a UAC elevation) var retryResult = await OptimizationService.RetryFailedStepsWithResultsAsync( failedSteps: result.FailedSteps, reverseOrder: false, logger: myLogger, progress: progressReporter ); Console.WriteLine($"Recovered: {retryResult.RecoveredSteps.Count}, Still failed: {retryResult.FailedSteps.Count}"); // Create a Windows restore point before applying changes RestorePointResult rpResult = await optimizationService.CreateRestorePointAsync(); // RestorePointResult: Success | Failed | FrequencyLimitReached ``` -------------------------------- ### Run Unit Tests Source: https://github.com/itsfatduck/optimizerduck/blob/master/AGENTS.md Execute unit tests using xUnit. The --no-build flag is used when tests are run after a successful build. ```bash dotnet test optimizerDuck.Test/optimizerDuck.Test.csproj --configuration Release --no-build ``` -------------------------------- ### Implement Binary Toggle for Windows Features with IFeature Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Use IFeature and RegistryToggle to create binary toggles for Windows features. BaseFeature handles state reading and modification, with an option to restart Explorer. ```csharp [FeatureCategory(PageType = typeof(DesktopFeatureCategory))] public class Desktop : IFeatureCategory { public string Name => Loc.Instance[$"Features.{nameof(Desktop)}.Name"]; public SymbolRegular Icon { get; init; } = SymbolRegular.Desktop16; public FeatureCategoryOrder Order { get; init; } = FeatureCategoryOrder.Desktop; public ObservableCollection Features { get; init; } = []; [Feature(Section = nameof(Sections.Icons), Icon = SymbolRegular.Laptop24)] public class ShowThisPc : BaseFeature { protected override bool NeedsPostAction => true; // restarts Explorer protected override IEnumerable RegistryToggles => [ new() { Path = @"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel", Name = "{20D04FE0-3AEA-1069-A2D8-08002B30309D}", OnValue = 0, // 0 = show icon OffValue = 1, // 1 = hide icon DefaultValue = 0, } ]; } } // Programmatic usage (e.g., from a ViewModel): IFeature feature = new Desktop.ShowThisPc(); bool isEnabled = await feature.GetStateAsync(); // true if icon is visible await feature.EnableAsync(); // shows "This PC" on desktop, restarts Explorer await feature.DisableAsync(); // hides "This PC", restarts Explorer ``` -------------------------------- ### Publish Release Artifacts Source: https://github.com/itsfatduck/optimizerduck/blob/master/AGENTS.md Create release artifacts for the application. Supports 'portable' or 'single' output types. The --skip-tests flag can be used to exclude tests from the publishing process. ```bash publish.bat portable ``` ```bash publish.bat single --skip-tests ``` -------------------------------- ### Create Serializable Undo Unit with IRevertStep Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Implement IRevertStep for serializable undo operations. Steps are persisted as JSON and can be executed to revert changes. ```csharp // RegistryRevertStep — restores or deletes a registry value var revertStep = new RegistryRevertStep { Action = RevertAction.RestorePrevious, Path = @"HKLM\SYSTEM\CurrentControlSet\Control\PriorityControl", Name = "Win32PrioritySeparation", Value = 2, // original value captured before the write Kind = RegistryValueKind.DWord, }; // Serialized to JSON for persistence: JObject json = revertStep.ToData(); // { // "Action": "RestorePrevious", // "Path": "HKLM\\SYSTEM\\...", // "Name": "Win32PrioritySeparation", // "Kind": "DWord", // "Value": 2 // } bool success = await revertStep.ExecuteAsync(); // restores the original value // ShellRevertStep — re-runs a command to undo a shell-based change var shellRevert = new ShellRevertStep { ShellType = ShellType.PowerShell, Command = "Set-ItemProperty -Path 'HKLM:\'... -Name 'Key' -Value 0" }; await shellRevert.ExecuteAsync(); ``` -------------------------------- ### Discover and Load Feature Toggles with FeatureRegistry Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Mirrors `OptimizationRegistry` for the feature toggle system. Registers categories and allows access to feature states and navigation items. ```csharp var featureRegistry = new FeatureRegistry(); featureRegistry.RegisterCategories(); ``` ```csharp foreach (var category in featureRegistry.Categories) { Console.WriteLine($"Category: {category.Name}"); foreach (var feature in category.Features) { bool state = await feature.GetStateAsync(); Console.WriteLine($" {feature.Name}: {(state ? "ON" : "OFF")}"); } } ``` ```csharp // Get WPF NavigationViewItems for the sidebar IEnumerable navItems = featureRegistry.GetNavigationItems(); ``` -------------------------------- ### RegistryService - Safe Registry Read/Write with Auto-Revert Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Provides a static service for safe registry operations. All write and delete operations automatically capture the previous value and register a revert step. It supports writing, reading, deleting values, checking key existence, creating subkeys, and deleting subkey trees. ```APIDOC ## RegistryService ### Description A static service for performing safe read and write operations on the Windows registry. It automatically handles the creation of revert steps for write and delete operations, ensuring that changes can be undone. ### Methods - `Write(params RegistryItem[] items)`: Writes one or multiple registry values. - `Read(RegistryItem item)`: Reads a registry value and attempts to cast it to the specified type `T`. - `DeleteValue(RegistryItem item)`: Deletes a registry value. - `KeyExists(RegistryItem item)`: Checks if a registry key exists. - `CreateSubKey(RegistryItem item)`: Creates a new registry subkey. - `DeleteSubKeyTree(RegistryItem item)`: Deletes an entire registry subkey tree. - `CleanupEmptyKeys(List createdSubKeys)`: Cleans up empty registry keys that were auto-created. ### Usage Examples ```csharp // Write one or multiple values (params overload) RegistryService.Write( new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile", "NetworkThrottlingIndex", unchecked((int)0xFFFFFFFF), RegistryValueKind.DWord), new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile", "SystemResponsiveness", 10) ); // Read a typed value int? threshold = RegistryService.Read( new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control", "SvcHostSplitThresholdInKB")); // Delete a value (records revert step automatically) RegistryService.DeleteValue(new RegistryItem(@"HKLM\SOFTWARE\SomeKey", "SomeValue")); // Check key existence bool exists = RegistryService.KeyExists(new RegistryItem(@"HKCU\Software\MyApp", null)); // Create a subkey (also tracked for revert) RegistryService.CreateSubKey(new RegistryItem(@"HKCU\Software\MyApp\NewKey", null)); // Delete entire subkey tree (backs up the tree first, up to 5000 entries) RegistryService.DeleteSubKeyTree(new RegistryItem(@"HKCU\Software\MyApp\OldKey", null)); // Cleanup empty keys that were auto-created during an operation // RegistryService.CleanupEmptyKeys(createdSubKeysList); ``` ``` -------------------------------- ### Using ExecutionScope for Operation Context Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Manages ambient, async-local context for service operations, tracking steps, logging timing statistics, and reporting results. Scopes are typically created internally but can be used manually. ```csharp // Scopes are created by OptimizationService internally, but can be used manually: using var scope = ExecutionScope.Begin(optimization, logger); // Services automatically call these via ExecutionScope.Current: ExecutionScope.RecordStep( name: "Registry", description: "Write HKLM\...\Win32PrioritySeparation", success: true, revertStep: new RegistryRevertStep { ... }, error: null, retryAction: null ); ExecutionScope.Track("RegistryService", success: true); ExecutionScope.LogInfo("Applied registry tweak: {Key}", "Win32PrioritySeparation"); ExecutionScope.LogWarning("Non-critical issue: {Msg}", "Value already set"); ExecutionScope.LogError(null, "Failed to write {Path}", @"HKLM\..."); // After all operations: bool hasWork = scope.HasSuccessfulSteps; // true if ≥1 step succeeded OptimizationResult result = scope.ToResult(); // result.Status: Success | PartialSuccess | Failed // result.FailedSteps: list of steps that failed List steps = scope.GetStepResults(); foreach (var step in steps) Console.WriteLine($"[{(step.Success ? "OK" : "FAIL")}] {step.Name}: {step.Description}"); // Disposing scope prints: "Completed in 00:01.234 | Registry: +(3) -(0), Shell: +(1) -(0)" ``` -------------------------------- ### Save and Revert Optimizations with RevertManager Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Persists and executes revert data for optimizations. Saves revert data from an ExecutionScope and allows reverting steps in reverse order. Use to undo applied optimizations. ```csharp await revertManager.SaveRevertDataAsync(executionScope); // Writes to: %AppData%\optimizerDuck\Revert\{optimizationId}.json // Example JSON: // { // "OptimizationId": "648ec19a-fda5-4607-8a7c-148b8b05fb4c", // "OptimizationName": "DisableBackgroundApps", // "AppliedAt": "2025-01-15T10:30:00", // "Steps": [ // { "Type": "Registry", "Data": { "Action": "RestorePrevious", "Path": "HKCU\...", ... } } // ] // } ``` ```csharp // Revert — steps are executed in reverse order RevertResult result = await revertManager.RevertAsync(optimization, progressReporter); Console.WriteLine(result.Success); // true if all steps reverted Console.WriteLine(result.AllStepsFailed); // true if nothing reverted Console.WriteLine(result.Message); ``` ```csharp // Check if revert data exists (i.e., optimization is applied) bool hasRevertData = await RevertManager.IsAppliedAsync(optimizationId); ``` ```csharp // Load raw revert data for inspection RevertData? data = await RevertManager.GetRevertDataAsync(optimizationId); Console.WriteLine(data?.AppliedAt); Console.WriteLine(data?.Steps.Count); ``` ```csharp // Clear all revert data (e.g., "reset everything") RevertManager.ClearAllRevertData(logger); ``` ```csharp // Upsert a single step at a specific index (for incremental updates) await revertManager.UpsertRevertStepAtIndexAsync( id: optimization.Id, name: optimization.OptimizationKey, stepIndex: 1, step: new RegistryRevertStep { Action = RevertAction.NoPreviousValue, Path = @"HKCU\..." } ); ``` -------------------------------- ### Perform Safe Registry Operations with RegistryService Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Utilize the static RegistryService for safe registry read/write operations. All write and delete operations automatically capture previous values for reverting. ```csharp // Write one or multiple values (params overload) RegistryService.Write( new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile", "NetworkThrottlingIndex", unchecked((int)0xFFFFFFFF), RegistryValueKind.DWord), new RegistryItem(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile", "SystemResponsiveness", 10) ); // Read a typed value int? threshold = RegistryService.Read( new RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control", "SvcHostSplitThresholdInKB")); // Delete a value (records revert step automatically) RegistryService.DeleteValue(new RegistryItem(@"HKLM\SomeKey", "SomeValue")); // Check key existence bool exists = RegistryService.KeyExists(new RegistryItem(@"HKCU\Software\MyApp", null)); // Create a subkey (also tracked for revert) RegistryService.CreateSubKey(new RegistryItem(@"HKCU\Software\MyApp\NewKey", null)); // Delete entire subkey tree (backs up the tree first, up to 5000 entries) RegistryService.DeleteSubKeyTree(new RegistryItem(@"HKCU\Software\MyApp\OldKey", null)); // Cleanup empty keys that were auto-created during an operation RegistryService.CleanupEmptyKeys(createdSubKeysList); ``` -------------------------------- ### Execute PowerShell Commands with Revert Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Runs PowerShell commands synchronously or asynchronously with optional revert commands. Handles UTF-8 output and records execution duration. Supports custom success exit codes. ```csharp // Run a PowerShell command (sync); revert command provided as a string ShellResult result = ShellService.PowerShell( "Set-Service -Name 'SysMain' -StartupType Disabled; Stop-Service -Name 'SysMain'", "Set-Service -Name 'SysMain' -StartupType Automatic; Start-Service -Name 'SysMain'" ); Console.WriteLine(result.ExitCode); // 0 = success Console.WriteLine(result.Stdout); Console.WriteLine(result.Stderr); Console.WriteLine(result.Duration); // TimeSpan // Run asynchronously with cancellation ShellResult asyncResult = await ShellService.PowerShellAsync( "Get-AppxPackage -Name 'Microsoft.BingWeather' | Remove-AppxPackage", policy: ShellPolicy.SuccessExitCodes(0, 1) // treat exit code 1 as success too ); // CMD execution with revert command ShellResult cmdResult = ShellService.CMD( "netsh advfirewall set allprofiles state off", "netsh advfirewall set allprofiles state on" ); // Custom success policy (e.g., allow any exit code 0–3) var lenient = ShellPolicy.SuccessExitCodeRange(3); ShellResult lenientResult = ShellService.PowerShell("sfc /scannow", policy: lenient); ``` -------------------------------- ### Declaring and Using RegistryToggle Source: https://context7.com/itsfatduck/optimizerduck/llms.txt Pairs on/off values for a registry key, handling state detection and modification. Useful for declarative feature state management. SetState deletes the value if OnValue or OffValue is null. ```csharp // Declare a toggle (typically inside a BaseFeature subclass) var toggle = new RegistryToggle { Path = @"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", Name = "HideFileExt", OnValue = 0, // 0 = show extensions (feature "on") OffValue = 1, // 1 = hide extensions (feature "off") DefaultValue = 1, TreatMissingAsDefault = true, ValueKind = RegistryValueKind.DWord, }; bool isOn = toggle.GetState(); // true if registry value == OnValue (0) toggle.SetState(true); // writes 0 (OnValue) toggle.SetState(false); // writes 1 (OffValue) // If OnValue or OffValue is null, SetState deletes the registry value instead of writing // String-value toggle example var themeToggle = new RegistryToggle { Path = @"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", Name = "AppsUseLightTheme", OnValue = 0, // dark mode OffValue = 1, // light mode ValueKind = RegistryValueKind.DWord, }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.