Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

refactor: Windows refresh logic with granular RefreshScope

fatDuck52eb1dd5bb7b
diff --git a/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs b/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs
index d201668..523d691 100644
--- a/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs
+++ b/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs
@@ -2,11 +2,6 @@ using optimizerDuck.Common.Helpers;
namespace optimizerDuck.Test.Common.Helpers;
-/// <summary>
-/// Integration-style smoke tests for <see cref="SystemRefreshService"/>.
-/// These call the actual Win32 API — they verify the P/Invoke signatures
-/// are correct and the service doesn't throw.
-/// </summary>
public class SystemRefreshServiceTests
{
[Fact]
@@ -26,7 +21,6 @@ public class SystemRefreshServiceTests
[Fact]
public void NotifySettingChange_ThenRefreshShell_DoesNotThrow()
{
- // Simulate the call sequence ExecutePostActionAsync would make
var exception1 = Record.Exception(() => SystemRefreshService.NotifySettingChange());
Assert.Null(exception1);
@@ -43,4 +37,82 @@ public class SystemRefreshServiceTests
Assert.Null(exception);
}
}
+
+ [Fact]
+ public void NotifyTaskbarSettingChange_DoesNotThrow()
+ {
+ var exception = Record.Exception(() =>
+ SystemRefreshService.NotifyTaskbarSettingChange()
+ );
+ Assert.Null(exception);
+ }
+
+ [Fact]
+ public void RefreshDesktop_DoesNotThrow()
+ {
+ var exception = Record.Exception(() => SystemRefreshService.RefreshDesktop());
+ Assert.Null(exception);
+ }
+
+ [Fact]
+ public void UpdatePerUserSystemParameters_DoesNotThrow()
+ {
+ var exception = Record.Exception(() =>
+ SystemRefreshService.UpdatePerUserSystemParameters()
+ );
+ Assert.Null(exception);
+ }
+
+ [Fact]
+ public void NotifyThemeChanged_DoesNotThrow()
+ {
+ var exception = Record.Exception(() => SystemRefreshService.NotifyThemeChanged());
+ Assert.Null(exception);
+ }
+
+ [Fact]
+ public void SetDesktopIconsVisible_True_DoesNotThrow()
+ {
+ var exception = Record.Exception(() =>
+ SystemRefreshService.SetDesktopIconsVisible(showIcons: true)
+ );
+ Assert.Null(exception);
+ }
+
+ [Fact]
+ public void SetDesktopIconsVisible_False_DoesNotThrow()
+ {
+ var exception = Record.Exception(() =>
+ SystemRefreshService.SetDesktopIconsVisible(showIcons: false)
+ );
+ Assert.Null(exception);
+ }
+
+ [Fact]
+ public void RefreshDesktopIconVisibilityFromRegistry_DoesNotThrow()
+ {
+ var exception = Record.Exception(() =>
+ SystemRefreshService.RefreshDesktopIconVisibilityFromRegistry()
+ );
+ Assert.Null(exception);
+ }
+
+ [Fact]
+ public void SetDesktopIconsVisible_ToggleBackAndForth_DoesNotThrow()
+ {
+ var ex1 = Record.Exception(() =>
+ SystemRefreshService.SetDesktopIconsVisible(showIcons: true)
+ );
+ Assert.Null(ex1);
+
+ var ex2 = Record.Exception(() =>
+ SystemRefreshService.SetDesktopIconsVisible(showIcons: false)
+ );
+ Assert.Null(ex2);
+
+ var ex3 = Record.Exception(() =>
+ SystemRefreshService.SetDesktopIconsVisible(showIcons: true)
+ );
+ Assert.Null(ex3);
+ }
}
diff --git a/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs b/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs
index e4a1ba5..11ea7a6 100644
--- a/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs
+++ b/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs
@@ -286,4 +286,196 @@ public class BaseCustomizeSettingTests : IDisposable
}
#endregion
+
+ #region RefreshScope tests
+
+ private static readonly System.Reflection.PropertyInfo RefreshScopeProperty =
+ typeof(BaseCustomizeSetting).GetProperty(
+ "RefreshScope",
+ System.Reflection.BindingFlags.Instance
+ | System.Reflection.BindingFlags.NonPublic
+ | System.Reflection.BindingFlags.Public
+ )!;
+
+ private static readonly System.Reflection.PropertyInfo NeedsPostActionProperty =
+ typeof(BaseCustomizeSetting).GetProperty(
+ "NeedsPostAction",
+ System.Reflection.BindingFlags.Instance
+ | System.Reflection.BindingFlags.NonPublic
+ | System.Reflection.BindingFlags.Public
+ )!;
+
+ private static CustomizeRefreshScope GetRefreshScope(BaseCustomizeSetting s) =>
+ (CustomizeRefreshScope)RefreshScopeProperty.GetValue(s)!;
+
+ private static bool GetNeedsPostAction(BaseCustomizeSetting s) =>
+ (bool)NeedsPostActionProperty.GetValue(s)!;
+
+ /// <summary>Plain setting with no overrides - must be opt-in for post-action.</summary>
+ private sealed class DefaultScopeSetting : BaseCustomizeSetting
+ {
+ public override Task<bool> GetStateAsync() => Task.FromResult(false);
+ }
+
+ /// <summary>Setting that opts into the default explorer-level refresh.</summary>
+ private sealed class DefaultExplorerScopeSetting : BaseCustomizeSetting
+ {
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Default;
+
+ public override Task<bool> GetStateAsync() => Task.FromResult(false);
+ }
+
+ /// <summary>Setting that opts into the desktop-icon refresh.</summary>
+ private sealed class DesktopIconsScopeSetting : BaseCustomizeSetting
+ {
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.DesktopIcons;
+
+ public override Task<bool> GetStateAsync() => Task.FromResult(false);
+ }
+
+ /// <summary>Setting that opts into the global HideIcons cache refresh.</summary>
+ private sealed class HideDesktopIconsScopeSetting : BaseCustomizeSetting
+ {
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.HideDesktopIcons;
+
+ public override Task<bool> GetStateAsync() => Task.FromResult(false);
+ }
+
+ /// <summary>Setting that opts into the taskbar refresh.</summary>
+ private sealed class TaskbarScopeSetting : BaseCustomizeSetting
+ {
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.TaskbarSettings;
+
+ public override Task<bool> GetStateAsync() => Task.FromResult(false);
+ }
+
+ /// <summary>Setting that opts into a multi-flag custom scope.</summary>
+ private sealed class MultiScopeSetting : BaseCustomizeSetting
+ {
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.Settings
+ | CustomizeRefreshScope.Associations
+ | CustomizeRefreshScope.PolicyUpdate;
+
+ public override Task<bool> GetStateAsync() => Task.FromResult(false);
+ }
+
+ [Fact]
+ public void RefreshScope_ByDefault_IsNone_SoPostActionDoesNotRun()
+ {
+ var setting = new DefaultScopeSetting();
+
+ Assert.Equal(CustomizeRefreshScope.None, GetRefreshScope(setting));
+ Assert.False(GetNeedsPostAction(setting));
+ }
+
+ [Fact]
+ public void NeedsPostAction_IsDerivedFromRefreshScope()
+ {
+ Assert.True(GetNeedsPostAction(new DefaultExplorerScopeSetting()));
+ Assert.True(GetNeedsPostAction(new DesktopIconsScopeSetting()));
+ Assert.True(GetNeedsPostAction(new HideDesktopIconsScopeSetting()));
+ Assert.True(GetNeedsPostAction(new TaskbarScopeSetting()));
+ Assert.True(GetNeedsPostAction(new MultiScopeSetting()));
+ Assert.False(GetNeedsPostAction(new DefaultScopeSetting()));
+ }
+
+ [Fact]
+ public void RefreshScope_OnEachSubclass_MatchesExpectedValue()
+ {
+ Assert.Equal(CustomizeRefreshScope.Default, GetRefreshScope(new DefaultExplorerScopeSetting()));
+ Assert.Equal(CustomizeRefreshScope.DesktopIcons, GetRefreshScope(new DesktopIconsScopeSetting()));
+ Assert.Equal(CustomizeRefreshScope.TaskbarSettings, GetRefreshScope(new TaskbarScopeSetting()));
+ Assert.Equal(
+ CustomizeRefreshScope.Settings
+ | CustomizeRefreshScope.Associations
+ | CustomizeRefreshScope.PolicyUpdate,
+ GetRefreshScope(new MultiScopeSetting())
+ );
+ }
+
+ [Fact]
+ public async Task ApplyAsync_WhenRefreshScopeIsNone_DoesNotCallPostAction()
+ {
+ var setting = new DefaultScopeSetting { OwnerType = typeof(DefaultScopeSetting) };
+
+ // With RefreshScope = None, the base ApplyAsync must skip
+ // ExecutePostActionAsync entirely. We confirm the gate behaviour:
+ // NeedsPostAction is false, so no refresh runs.
+ Assert.False(GetNeedsPostAction(setting));
+ await setting.ApplyAsync(false); // must not throw
+ }
+
+ [Fact]
+ public async Task ApplyAsync_WhenRefreshScopeIsSet_RunsWithoutThrowing()
+ {
+ // Smoke test: every declared scope variant must produce a working
+ // ApplyAsync that touches the registry and runs the refresh pipeline
+ // without exceptions on a real Windows host.
+ var settings = new BaseCustomizeSetting[]
+ {
+ new DefaultExplorerScopeSetting { OwnerType = typeof(DefaultExplorerScopeSetting) },
+ new DesktopIconsScopeSetting { OwnerType = typeof(DesktopIconsScopeSetting) },
+ new TaskbarScopeSetting { OwnerType = typeof(TaskbarScopeSetting) },
+ new MultiScopeSetting { OwnerType = typeof(MultiScopeSetting) },
+ };
+
+ foreach (var setting in settings)
+ {
+ await setting.ApplyAsync(true);
+ await setting.ApplyAsync(false);
+ }
+ }
+
+ [Fact]
+ public void CustomizeRefreshScope_DefaultEqualsSettingsPlusAssociations()
+ {
+ Assert.Equal(
+ CustomizeRefreshScope.Settings | CustomizeRefreshScope.Associations,
+ CustomizeRefreshScope.Default
+ );
+ }
+
+ [Fact]
+ public void CustomizeRefreshScope_DesktopIconsEqualsSettingsPlusDesktop()
+ {
+ Assert.Equal(
+ CustomizeRefreshScope.Settings | CustomizeRefreshScope.Desktop,
+ CustomizeRefreshScope.DesktopIcons
+ );
+ }
+
+ [Fact]
+ public void CustomizeRefreshScope_TaskbarSettingsEqualsSettingsPlusTaskbar()
+ {
+ Assert.Equal(
+ CustomizeRefreshScope.Settings | CustomizeRefreshScope.Taskbar,
+ CustomizeRefreshScope.TaskbarSettings
+ );
+ }
+
+ [Fact]
+ public void CustomizeRefreshScope_ExplorerViewIncludesPolicyUpdate()
+ {
+ Assert.True(CustomizeRefreshScope.ExplorerView.HasFlag(CustomizeRefreshScope.PolicyUpdate));
+ }
+
+ [Fact]
+ public void CustomizeRefreshScope_AllFlagsCanBeCombined()
+ {
+ var all = CustomizeRefreshScope.Settings
+ | CustomizeRefreshScope.Associations
+ | CustomizeRefreshScope.Desktop
+ | CustomizeRefreshScope.Taskbar
+ | CustomizeRefreshScope.PolicyUpdate
+ | CustomizeRefreshScope.Theme;
+
+ Assert.True(all.HasFlag(CustomizeRefreshScope.Settings));
+ Assert.True(all.HasFlag(CustomizeRefreshScope.Theme));
+ }
+
+ #endregion
}
diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.cs
index 6265e0e..e136473 100644
--- a/optimizerDuck/App.xaml.cs
+++ b/optimizerDuck/App.xaml.cs
@@ -119,7 +119,23 @@ public partial class App : Application
private bool _allowClose;
private IContentDialogService? _contentDialogService = null;
- public bool HasPendingChanges { get; set; }
+ private bool _hasPendingChanges;
+
+ public bool HasPendingChanges
+ {
+ get => _hasPendingChanges;
+ set
+ {
+ if (_hasPendingChanges == value)
+ return;
+ _hasPendingChanges = value;
+ Dispatcher.InvokeAsync(() =>
+ {
+ if (Current.MainWindow is MainWindow mw)
+ mw.UpdatePendingIndicator(value);
+ });
+ }
+ }
protected override void OnStartup(StartupEventArgs e)
{
diff --git a/optimizerDuck/Common/Helpers/SystemRefreshService.cs b/optimizerDuck/Common/Helpers/SystemRefreshService.cs
index cfda467..6a8ceb9 100644
--- a/optimizerDuck/Common/Helpers/SystemRefreshService.cs
+++ b/optimizerDuck/Common/Helpers/SystemRefreshService.cs
@@ -1,25 +1,53 @@
-using System.Diagnostics;
using System.Runtime.InteropServices;
namespace optimizerDuck.Common.Helpers;
-/// <summary>
-/// Provides targeted Windows API-based refresh mechanisms instead of restarting Explorer.
-/// Uses WM_SETTINGCHANGE broadcasts and SHChangeNotify for shell/explorer settings.
-/// </summary>
internal static class SystemRefreshService
{
- [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
+ #region P/Invoke declarations
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessageTimeout(
IntPtr hWnd,
uint Msg,
IntPtr wParam,
- string? lParam,
+ [MarshalAs(UnmanagedType.LPWStr)] string? lParam,
uint fuFlags,
uint uTimeout,
out IntPtr lpdwResult
);
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
+ private static extern IntPtr SendMessage(
+ IntPtr hWnd,
+ uint Msg,
+ IntPtr wParam,
+ IntPtr lParam
+ );
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ private static extern IntPtr FindWindow(string? lpClassName, string? lpWindowName);
+
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ private static extern IntPtr FindWindowEx(
+ IntPtr hWndParent,
+ IntPtr hWndChildAfter,
+ string? lpszClass,
+ string? lpszWindow
+ );
+
+ [DllImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool InvalidateRect(IntPtr hWnd, IntPtr lpRect, [MarshalAs(UnmanagedType.Bool)] bool bErase);
+
+ [DllImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool UpdateWindow(IntPtr hWnd);
+
+ [DllImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool IsWindowVisible(IntPtr hWnd);
+
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern void SHChangeNotify(
uint wEventId,
@@ -28,17 +56,44 @@ internal static class SystemRefreshService
IntPtr dwItem2
);
+ [DllImport("user32.dll", SetLastError = true)]
+ private static extern bool SystemParametersInfo(
+ uint uiAction,
+ uint uiParam,
+ IntPtr pvParam,
+ uint fWinIni
+ );
+
+ #endregion
+
+ #region Constants
+
private static readonly IntPtr HWND_BROADCAST = new(0xffff);
private const uint WM_SETTINGCHANGE = 0x001A;
+ private const uint WM_THEMECHANGED = 0x031A;
+ private const uint WM_COMMAND = 0x0111;
private const uint SMTO_ABORTIFHUNG = 0x0002;
private const uint SHCNE_ASSOCCHANGED = 0x08000000;
private const uint SHCNF_IDLIST = 0x0000;
+ private const uint SHCNF_FLUSH = 0x1000;
+
+ private const uint SPI_SETDESKWALLPAPER = 0x0014;
+ private const uint SPIF_UPDATEINIFILE = 0x01;
+ private const uint SPIF_SENDCHANGE = 0x02;
+
+ private static readonly IntPtr TOGGLE_DESKTOP_ICONS = 0x7402;
+
+ private const uint LVM_REFRESH = 0x1033;
+ private const uint LVM_UPDATE = 0x102D;
+
+ private const string PROGMAN_CLASS = "Progman";
+ private const string SHELLDLL_DEFVIEW = "SHELLDLL_DefView";
+ private const string SYSLISTVIEW32 = "SysListView32";
+ private const string WORKERW_CLASS = "WorkerW";
+
+ #endregion
- /// <summary>
- /// Broadcasts a WM_SETTINGCHANGE to all top-level windows, telling them
- /// to re-read their registry settings. Suitable for most system settings.
- /// </summary>
public static void NotifySettingChange()
{
SendMessageTimeout(
@@ -52,47 +107,168 @@ internal static class SystemRefreshService
);
}
- /// <summary>
- /// Notifies shell/explorer that a setting affecting file view or shell behavior has changed.
- /// Equivalent to refreshing File Explorer without restarting it.
- /// </summary>
+ public static void NotifyTaskbarSettingChange()
+ {
+ SendMessageTimeout(
+ HWND_BROADCAST,
+ WM_SETTINGCHANGE,
+ IntPtr.Zero,
+ "TraySettings",
+ SMTO_ABORTIFHUNG,
+ 100,
+ out _
+ );
+ }
+
public static void RefreshShell()
{
+ SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST | SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero);
+ }
+
+ public static void RefreshDesktop()
+ {
+ SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST | SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero);
+
+ foreach (var listView in EnumerateDesktopListViews())
+ {
+ SendMessage(listView, LVM_REFRESH, IntPtr.Zero, IntPtr.Zero);
+ SendMessage(listView, LVM_UPDATE, IntPtr.Zero, IntPtr.Zero);
+
+ InvalidateRect(listView, IntPtr.Zero, true);
+ UpdateWindow(listView);
+ }
+ }
+
+ public static void SetDesktopIconsVisible(bool showIcons)
+ {
+ var defView = FindDesktopDefView();
+ if (defView == IntPtr.Zero)
+ return;
+
+ var listView = FindWindowEx(defView, IntPtr.Zero, SYSLISTVIEW32, null);
+ var currentlyVisible = listView != IntPtr.Zero && IsWindowVisible(listView);
+
+ if (currentlyVisible != showIcons)
+ SendMessage(defView, WM_COMMAND, TOGGLE_DESKTOP_ICONS, IntPtr.Zero);
+
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
}
- /// <summary>
- /// As a last resort, if targeted refreshes don't work, we can restart Explorer
- /// </summary>
- public static void RestartExplorer()
+ public static void RefreshDesktopIconVisibilityFromRegistry()
{
- Process.Start(
- new ProcessStartInfo
+ var showIcons = true;
+ try
+ {
+ using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
+ @"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ writable: false
+ );
+ var raw = key?.GetValue("HideIcons");
+ var value = raw switch
{
- FileName = "cmd.exe",
- Arguments = "/c taskkill /f /im explorer.exe && start explorer.exe",
- CreateNoWindow = true,
- UseShellExecute = false,
- }
+ int i => i,
+ long l => (int)l,
+ _ => 0,
+ };
+ showIcons = value == 0;
+ }
+ catch (System.Security.SecurityException)
+ {
+ }
+ catch (System.IO.IOException)
+ {
+ }
+ catch (UnauthorizedAccessException)
+ {
+ }
+
+ SetDesktopIconsVisible(showIcons);
+ }
+
+ public static void UpdatePerUserSystemParameters()
+ {
+ SystemParametersInfo(
+ SPI_SETDESKWALLPAPER,
+ 0,
+ IntPtr.Zero,
+ SPIF_UPDATEINIFILE | SPIF_SENDCHANGE
+ );
+ }
+
+ public static void NotifyThemeChanged()
+ {
+ SendMessageTimeout(
+ HWND_BROADCAST,
+ WM_THEMECHANGED,
+ IntPtr.Zero,
+ null,
+ SMTO_ABORTIFHUNG,
+ 100,
+ out _
);
}
- /// <summary>
- /// As a last resort, if targeted refreshes don't work, we can restart Explorer
- /// </summary>
- public static Task RestartExplorerAsync()
+ private static IntPtr FindDesktopDefView()
{
- return Task.Run(() =>
+ var progman = FindWindow(PROGMAN_CLASS, null);
+ if (progman != IntPtr.Zero)
{
- Process.Start(
- new ProcessStartInfo
- {
- FileName = "cmd.exe",
- Arguments = "/c taskkill /f /im explorer.exe && start explorer.exe",
- CreateNoWindow = true,
- UseShellExecute = false,
- }
- );
- });
+ var defView = FindWindowEx(progman, IntPtr.Zero, SHELLDLL_DEFVIEW, null);
+ if (defView != IntPtr.Zero)
+ return defView;
+ }
+
+ var worker = FindWindowEx(IntPtr.Zero, IntPtr.Zero, WORKERW_CLASS, null);
+ while (worker != IntPtr.Zero)
+ {
+ var defView = FindWindowEx(worker, IntPtr.Zero, SHELLDLL_DEFVIEW, null);
+ if (defView != IntPtr.Zero)
+ return defView;
+
+ worker = FindWindowEx(IntPtr.Zero, worker, WORKERW_CLASS, null);
+ }
+
+ return IntPtr.Zero;
+ }
+
+ private static IEnumerable<IntPtr> EnumerateDesktopListViews()
+ {
+ var seen = new HashSet<IntPtr>();
+
+ var progman = FindWindow(PROGMAN_CLASS, null);
+ if (progman != IntPtr.Zero)
+ {
+ foreach (var lv in EnumerateListViewsUnder(progman))
+ {
+ if (seen.Add(lv))
+ yield return lv;
+ }
+ }
+
+ var worker = FindWindowEx(IntPtr.Zero, IntPtr.Zero, WORKERW_CLASS, null);
+ while (worker != IntPtr.Zero)
+ {
+ foreach (var lv in EnumerateListViewsUnder(worker))
+ {
+ if (seen.Add(lv))
+ yield return lv;
+ }
+
+ worker = FindWindowEx(IntPtr.Zero, worker, WORKERW_CLASS, null);
+ }
+ }
+
+ private static IEnumerable<IntPtr> EnumerateListViewsUnder(IntPtr host)
+ {
+ var defView = FindWindowEx(host, IntPtr.Zero, SHELLDLL_DEFVIEW, null);
+ if (defView == IntPtr.Zero)
+ yield break;
+
+ var listView = FindWindowEx(defView, IntPtr.Zero, SYSLISTVIEW32, null);
+ while (listView != IntPtr.Zero)
+ {
+ yield return listView;
+ listView = FindWindowEx(defView, listView, SYSLISTVIEW32, null);
+ }
}
}
diff --git a/optimizerDuck/Domain/Customize/Categories/Desktop.cs b/optimizerDuck/Domain/Customize/Categories/Desktop.cs
index 4daf0f4..9cfff51 100644
--- a/optimizerDuck/Domain/Customize/Categories/Desktop.cs
+++ b/optimizerDuck/Domain/Customize/Categories/Desktop.cs
@@ -30,7 +30,7 @@ public class Desktop : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Icons), Icon = SymbolRegular.Laptop24)]
public class ShowThisPc : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.DesktopIcons;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -49,7 +49,7 @@ public class Desktop : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Icons), Icon = SymbolRegular.Delete24)]
public class ShowRecycleBin : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.DesktopIcons;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -68,7 +68,7 @@ public class Desktop : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Icons), Icon = SymbolRegular.Folder24)]
public class ShowUserFiles : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.DesktopIcons;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -87,7 +87,7 @@ public class Desktop : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Icons), Icon = SymbolRegular.Desktop24)]
public class ShowNetwork : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.DesktopIcons;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -106,7 +106,7 @@ public class Desktop : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Icons), Icon = SymbolRegular.Grid24)]
public class ShowControlPanel : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.DesktopIcons;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -125,14 +125,15 @@ public class Desktop : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Icons), Icon = SymbolRegular.Desktop24)]
public class ShowDesktopIcons : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.HideDesktopIcons;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
{
- Path = @"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer",
- Name = "NoDesktop",
+ Path = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
+ Name = "HideIcons",
OnValue = 0,
OffValue = 1,
DefaultValue = 0,
@@ -173,6 +174,9 @@ public class Desktop : ICustomizeCategory
|| fileName.Equals("blankicon.ico", StringComparison.OrdinalIgnoreCase);
}
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.Associations | CustomizeRefreshScope.PolicyUpdate;
+
protected override IReadOnlyList<string> GetWatchedRegistryPaths() => [Path];
public override Task<bool> GetStateAsync()
diff --git a/optimizerDuck/Domain/Customize/Categories/Gaming.cs b/optimizerDuck/Domain/Customize/Categories/Gaming.cs
index b6769f3..33c1b7d 100644
--- a/optimizerDuck/Domain/Customize/Categories/Gaming.cs
+++ b/optimizerDuck/Domain/Customize/Categories/Gaming.cs
@@ -34,6 +34,8 @@ public class Gaming : ICustomizeCategory
)]
public class GameMode : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Settings;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -62,6 +64,8 @@ public class Gaming : ICustomizeCategory
)]
public class GameBar : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Settings;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -109,6 +113,9 @@ public class Gaming : ICustomizeCategory
)]
public class BackgroundRecording : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.Settings | CustomizeRefreshScope.PolicyUpdate;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -165,6 +172,9 @@ public class Gaming : ICustomizeCategory
{
private const string Path = @"HKCU\Control Panel\Mouse";
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.PolicyUpdate;
+
protected override IReadOnlyList<string> GetWatchedRegistryPaths() => [Path];
public override Task<bool> GetStateAsync()
@@ -210,6 +220,8 @@ public class Gaming : ICustomizeCategory
)]
public class FullscreenOptimizations : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Settings;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
diff --git a/optimizerDuck/Domain/Customize/Categories/Preferences.cs b/optimizerDuck/Domain/Customize/Categories/Preferences.cs
index 722c19d..6a06622 100644
--- a/optimizerDuck/Domain/Customize/Categories/Preferences.cs
+++ b/optimizerDuck/Domain/Customize/Categories/Preferences.cs
@@ -52,7 +52,8 @@ public class Preferences : ICustomizeCategory
await ExecutePostActionAsync();
}
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.TaskbarSettings;
protected override IReadOnlyList<string> GetWatchedRegistryPaths() => [RegPath];
}
@@ -64,7 +65,8 @@ public class Preferences : ICustomizeCategory
)]
public class TaskbarWidgets : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.TaskbarSettings;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -100,7 +102,8 @@ public class Preferences : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Taskbar), Icon = SymbolRegular.DesktopMac24)]
public class TaskbarTaskViewButton : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.TaskbarSettings;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -122,6 +125,9 @@ public class Preferences : ICustomizeCategory
)]
public class TaskbarEndTask : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.TaskbarSettings;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -139,6 +145,9 @@ public class Preferences : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Appearance), Icon = SymbolRegular.DarkTheme24)]
public class DarkMode : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.Settings | CustomizeRefreshScope.Theme;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -167,7 +176,7 @@ public class Preferences : ICustomizeCategory
)]
public class ExplorerSyncNotifications : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Default;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -189,6 +198,8 @@ public class Preferences : ICustomizeCategory
)]
public class SystemSuggestions : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Settings;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -205,6 +216,8 @@ public class Preferences : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Explorer), Icon = SymbolRegular.Alert24)]
public class ToastNotifications : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Settings;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -230,7 +243,7 @@ public class Preferences : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Explorer), Icon = SymbolRegular.Table24)]
public class ExplorerCompactMode : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Default;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -248,7 +261,7 @@ public class Preferences : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Explorer), Icon = SymbolRegular.Grid24)]
public class SnapAssistFlyout : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Default;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -266,7 +279,7 @@ public class Preferences : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Explorer), Icon = SymbolRegular.CheckboxChecked24)]
public class ExplorerItemCheckboxes : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Default;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -288,7 +301,7 @@ public class Preferences : ICustomizeCategory
)]
public class ShowFileExtensions : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.ExplorerView;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -310,7 +323,7 @@ public class Preferences : ICustomizeCategory
)]
public class ShowHiddenFiles : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.ExplorerView;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -332,6 +345,8 @@ public class Preferences : ICustomizeCategory
)]
public class ClipboardHistory : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Settings;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -348,7 +363,7 @@ public class Preferences : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Explorer), Icon = SymbolRegular.CursorClick24)]
public class WindowShake : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Default;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -366,6 +381,9 @@ public class Preferences : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Taskbar), Icon = SymbolRegular.Clock24)]
public class ShowSecondsInSystemClock : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.TaskbarSettings;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -382,6 +400,8 @@ public class Preferences : ICustomizeCategory
[CustomizeSetting(Section = nameof(Sections.Explorer), Icon = SymbolRegular.Folder24)]
public class LaunchToThisPc : BaseCustomizeSetting
{
+ protected override CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.Default;
+
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
new()
@@ -402,7 +422,8 @@ public class Preferences : ICustomizeCategory
)]
public class BingSearch : BaseCustomizeSetting
{
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.TaskbarSettings;
protected override IEnumerable<RegistryToggle> RegistryToggles =>
[
@@ -429,7 +450,9 @@ public class Preferences : ICustomizeCategory
private const string InprocPath = BasePath + @"\InprocServer32";
- protected override bool NeedsPostAction => true;
+ protected override CustomizeRefreshScope RefreshScope =>
+ CustomizeRefreshScope.Default
+ | CustomizeRefreshScope.PolicyUpdate;
protected override IReadOnlyList<string> GetWatchedRegistryPaths() => [BasePath];
diff --git a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs
index a0083ff..4b855ce 100644
--- a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs
+++ b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs
@@ -3,7 +3,6 @@ using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
using optimizerDuck.Services.Managers;
-using optimizerDuck.Services.Optimization.Providers;
using Wpf.Ui.Controls;
namespace optimizerDuck.Domain.Customize.Models;
@@ -104,14 +103,49 @@ public abstract class BaseCustomizeSetting : ICustomizeSetting
protected virtual IReadOnlyList<string> GetWatchedRegistryPaths() =>
[.. RegistryToggles.Select(t => t.Path).Distinct(StringComparer.OrdinalIgnoreCase)];
- protected virtual bool NeedsPostAction => false;
-
+ /// <summary>
+ /// Whether the setting requires a Windows refresh after <see cref="ApplyAsync"/>.
+ /// Defaults to <c>false</c>; auto-derived from <see cref="RefreshScope"/> but
+ /// can be overridden for custom behaviour.
+ /// </summary>
+ protected virtual bool NeedsPostAction => RefreshScope != CustomizeRefreshScope.None;
+
+ /// <summary>
+ /// Granular set of Windows surfaces that must be notified after
+ /// <see cref="ApplyAsync"/>. Override this to declare exactly which
+ /// refresh strategies are required (e.g. <see cref="CustomizeRefreshScope.DesktopIcons"/>
+ /// for settings that affect the desktop icon list). Default is
+ /// <see cref="CustomizeRefreshScope.None"/> - opt in by overriding.
+ /// </summary>
+ protected virtual CustomizeRefreshScope RefreshScope => CustomizeRefreshScope.None;
+
+ /// <summary>
+ /// Runs every refresh strategy declared in <see cref="RefreshScope"/>.
+ /// Subclasses can override this to add custom Win32 work alongside or
+ /// instead of the default refresh pipeline.
+ /// </summary>
protected virtual async Task ExecutePostActionAsync()
{
+ var scope = RefreshScope;
+ if (scope == CustomizeRefreshScope.None)
+ return;
+
await Task.Run(() =>
{
- SystemRefreshService.NotifySettingChange();
- SystemRefreshService.RefreshShell();
+ if (scope.HasFlag(CustomizeRefreshScope.Settings))
+ SystemRefreshService.NotifySettingChange();
+ if (scope.HasFlag(CustomizeRefreshScope.Associations))
+ SystemRefreshService.RefreshShell();
+ if (scope.HasFlag(CustomizeRefreshScope.Desktop))
+ SystemRefreshService.RefreshDesktop();
+ if (scope.HasFlag(CustomizeRefreshScope.DesktopIconCache))
+ SystemRefreshService.RefreshDesktopIconVisibilityFromRegistry();
+ if (scope.HasFlag(CustomizeRefreshScope.Taskbar))
+ SystemRefreshService.NotifyTaskbarSettingChange();
+ if (scope.HasFlag(CustomizeRefreshScope.PolicyUpdate))
+ SystemRefreshService.UpdatePerUserSystemParameters();
+ if (scope.HasFlag(CustomizeRefreshScope.Theme))
+ SystemRefreshService.NotifyThemeChanged();
});
}
diff --git a/optimizerDuck/Domain/Customize/Models/CustomizeRefreshScope.cs b/optimizerDuck/Domain/Customize/Models/CustomizeRefreshScope.cs
new file mode 100644
index 0000000..e543d38
--- /dev/null
+++ b/optimizerDuck/Domain/Customize/Models/CustomizeRefreshScope.cs
@@ -0,0 +1,60 @@
+namespace optimizerDuck.Domain.Customize.Models;
+
+[Flags]
+public enum CustomizeRefreshScope
+{
+ /// <summary>No refresh.</summary>
+ None = 0,
+
+ /// <summary>Broadcast <c>WM_SETTINGCHANGE</c> so apps re-read registry.</summary>
+ Settings = 1 << 0,
+
+ /// <summary>
+ /// Notify the shell that file associations or icon cache changed
+ /// (<c>SHChangeNotify(SHCNE_ASSOCCHANGED)</c>).
+ /// </summary>
+ Associations = 1 << 1,
+
+ /// <summary>
+ /// Force the desktop icon list (<c>SysListView32</c>) to repaint so
+ /// changes to the {CLSID}-based desktop icon CLSIDs are visible immediately.
+ /// </summary>
+ Desktop = 1 << 2,
+
+ /// <summary>
+ /// Broadcast a taskbar-targeted <c>WM_SETTINGCHANGE</c> so the taskbar
+ /// re-evaluates alignment, widgets, and other tray items.
+ /// </summary>
+ Taskbar = 1 << 3,
+
+ /// <summary>
+ /// Push <c>SystemParametersInfo</c> with <c>SPIF_SENDCHANGE</c> so the
+ /// shell re-reads per-user system parameters (icon spacing, wallpaper,
+ /// visual effects).
+ /// </summary>
+ PolicyUpdate = 1 << 4,
+
+ /// <summary>Broadcast <c>WM_THEMECHANGED</c> for theme/visual tweaks.</summary>
+ Theme = 1 << 5,
+
+ /// <summary>
+ /// Toggles desktop icon visibility by reading the current <c>HideIcons</c>
+ /// registry value and sending <c>WM_COMMAND 0x7402</c> to the desktop's
+ /// </summary>
+ DesktopIconCache = 1 << 6,
+
+ /// <summary>Standard explorer-level settings (Settings + Associations).</summary>
+ Default = Settings | Associations,
+
+ /// <summary>Toggles affecting the desktop icon list.</summary>
+ DesktopIcons = Settings | Desktop,
+
+ /// <summary>Toggling the global "hide all desktop icons" flag (HideIcons).</summary>
+ HideDesktopIcons = Settings | DesktopIconCache,
+
+ /// <summary>Toggles affecting the taskbar.</summary>
+ TaskbarSettings = Settings | Taskbar,
+
+ /// <summary>File-explorer view options (Extensions/Hidden/etc.).</summary>
+ ExplorerView = Settings | Associations | PolicyUpdate,
+}
diff --git a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs
index 6907d3f..e1e1660 100644
--- a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs
+++ b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs
@@ -1,4 +1,5 @@
using System.Diagnostics;
+using System.Text.RegularExpressions;
using optimizerDuck.Common.Extensions;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
@@ -12,31 +13,53 @@ public static class ServiceProcessService
private static readonly AsyncLocal<string?> _lastError = new();
private static readonly AsyncLocal<string?> _lastErrorDetail = new();
+ private static readonly Regex _startTypeRegex = new(
+ @"START_TYPE\s*:\s*(\d+)",
+ RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase
+ );
+
+ private static readonly Regex _delayedRegex = new(
+ @"\(Delayed\)",
+ RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase
+ );
+
internal static string? LastError => _lastError.Value;
internal static string? LastErrorDetail => _lastErrorDetail.Value;
- /// <summary>Gets the current startup type of a Windows service from the registry.</summary>
- /// <param name="serviceName">The name of the service.</param>
- /// <returns>The startup type, or <see langword="null" /> if the value is unrecognized or an error occurs.</returns>
public static ServiceStartupType? GetStartupType(string serviceName)
{
try
{
- var serviceKey = $@"HKLM\SYSTEM\CurrentControlSet\Services\{serviceName}";
- var start = RegistryService.Read<int>(new RegistryItem(serviceKey, "Start"));
+ var (exitCode, stdout, stderr) = RunScExe($"qc \"{serviceName}\"", 15000);
- if (start == 2)
+ if (exitCode != 0)
{
- var isDelayed = RegistryService.Read<int>(
- new RegistryItem(serviceKey, "DelayedAutoStart")
+ ExecutionScope.LogWarning(
+ "[SERVICE][{Name}] sc.exe qc failed with exit code {ExitCode}: {Stderr}",
+ serviceName,
+ exitCode,
+ stderr
);
- return isDelayed == 1
- ? ServiceStartupType.AutomaticDelayedStart
- : ServiceStartupType.Automatic;
+ return null;
}
- return start switch
+ var startMatch = _startTypeRegex.Match(stdout);
+ if (!startMatch.Success)
{
+ ExecutionScope.LogWarning(
+ "[SERVICE][{Name}] Could not parse START_TYPE from sc.exe qc output",
+ serviceName
+ );
+ return null;
+ }
+
+ var startValue = int.Parse(startMatch.Groups[1].Value);
+
+ return startValue switch
+ {
+ 2 => _delayedRegex.IsMatch(stdout)
+ ? ServiceStartupType.AutomaticDelayedStart
+ : ServiceStartupType.Automatic,
3 => ServiceStartupType.Manual,
4 => ServiceStartupType.Disabled,
_ => null,
@@ -53,9 +76,6 @@ public static class ServiceProcessService
}
}
- /// <summary>Changes a service's startup type by writing the corresponding registry values.</summary>
- /// <param name="item">The service name and target startup type.</param>
- /// <returns><see langword="true" /> if the change succeeded; otherwise, <see langword="false" />.</returns>
public static bool ChangeServiceStartupType(ServiceItem item)
{
_lastError.Value = _lastErrorDetail.Value = null;
@@ -71,36 +91,27 @@ public static class ServiceProcessService
{
var originalStartupType = GetStartupType(item.Name);
- // Map ServiceStartupType to Registry 'Start' value
- var startValue = item.StartupType switch
+ var scType = item.StartupType switch
{
- ServiceStartupType.Automatic or ServiceStartupType.AutomaticDelayedStart => 2,
- ServiceStartupType.Manual => 3,
- ServiceStartupType.Disabled => 4,
- _ => 3,
+ ServiceStartupType.Automatic => "auto",
+ ServiceStartupType.AutomaticDelayedStart => "delayed-auto",
+ ServiceStartupType.Manual => "demand",
+ ServiceStartupType.Disabled => "disabled",
+ _ => "demand",
};
- var serviceKey = $@"HKLM\SYSTEM\CurrentControlSet\Services\{item.Name}";
-
- var mainSuccess = RegistryService.Write(
- new RegistryItem(serviceKey, "Start", startValue)
+ var (exitCode, stdout, stderr) = RunScExe(
+ $"config \"{item.Name}\" start= {scType}",
+ 30000
);
- var regError = RegistryService.LastError;
- var regErrorDetail = RegistryService.LastErrorDetail;
-
- // handle 'DelayedAutoStart' if necessary
- var delayedSuccess = true;
- if (item.StartupType == ServiceStartupType.AutomaticDelayedStart)
- delayedSuccess = RegistryService.Write(
- new RegistryItem(serviceKey, "DelayedAutoStart", 1)
- );
- else
- // Always try to delete for consistency, but don't fail if it doesn't exist
- RegistryService.DeleteValue(new RegistryItem(serviceKey, "DelayedAutoStart"));
- var success = mainSuccess && delayedSuccess;
+ var success = exitCode == 0;
sw.Stop();
+ if (!success)
+ _lastErrorDetail.Value =
+ $"sc.exe exit code: {exitCode}\nstdout: {stdout}\nstderr: {stderr}";
+
if (success)
{
ServiceRevertStep? revertStep = null;
@@ -129,8 +140,7 @@ public static class ServiceProcessService
}
_lastError.Value =
- regError ?? Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed;
- _lastErrorDetail.Value = regErrorDetail;
+ Translations.Service_Service_Error_UpdateRegistryForStartupTypeFailed;
ExecutionScope.LogInfo(
"[SERVICE][{Name}][FAIL][D={Duration}] startup -> {StartupType}",
item.Name,
@@ -157,6 +167,7 @@ public static class ServiceProcessService
ex.Message
);
_lastErrorDetail.Value = ex.ToString();
+
ExecutionScope.LogError(
ex,
"[SERVICE][{Name}][FAIL][EXCEPTION] startup -> {StartupType}",
@@ -177,6 +188,32 @@ public static class ServiceProcessService
}
}
+ private static (int ExitCode, string Stdout, string Stderr) RunScExe(
+ string arguments,
+ int timeoutMs)
+ {
+ using var process = new Process
+ {
+ StartInfo = new ProcessStartInfo
+ {
+ FileName = "sc.exe",
+ Arguments = arguments,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ },
+ };
+
+ process.Start();
+ var stdoutTask = process.StandardOutput.ReadToEndAsync();
+ var stderrTask = process.StandardError.ReadToEndAsync();
+ process.WaitForExit(timeoutMs);
+ Task.WaitAll(stdoutTask, stderrTask);
+
+ return (process.ExitCode, stdoutTask.Result, stderrTask.Result);
+ }
+
/// <summary>Changes the startup type for multiple services.</summary>
/// <param name="items">The service items to update.</param>
public static void ChangeServiceStartupType(params ServiceItem[] items)
diff --git a/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs b/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs
index fffc8c4..78e5ad5 100644
--- a/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs
@@ -132,7 +132,7 @@ public partial class CustomizeItemViewModel(
return;
}
- var state = await setting.GetStateWithRetryAsync(maxRetries: 2, delayMs: 50);
+ var state = await setting.GetStateWithRetryAsync(maxRetries: 4, delayMs: 80);
IsEnabled = state;
CurrentValue = setting.CurrentValue;
}
diff --git a/optimizerDuck/UI/Windows/MainWindow.xaml b/optimizerDuck/UI/Windows/MainWindow.xaml
index b8713c5..ab7f671 100644
--- a/optimizerDuck/UI/Windows/MainWindow.xaml
+++ b/optimizerDuck/UI/Windows/MainWindow.xaml
@@ -119,6 +119,7 @@
VerticalAlignment="Center"
Source="pack://application:,,,/Resources/Images/Duck.png" />
<ui:TextBlock
+ x:Name="AppTitleText"
Margin="0,0,6,0"
VerticalAlignment="Center"
FontTypography="Body"
diff --git a/optimizerDuck/UI/Windows/MainWindow.xaml.cs b/optimizerDuck/UI/Windows/MainWindow.xaml.cs
index 5b7a677..28c0991 100644
--- a/optimizerDuck/UI/Windows/MainWindow.xaml.cs
+++ b/optimizerDuck/UI/Windows/MainWindow.xaml.cs
@@ -48,6 +48,12 @@ public partial class MainWindow : IWindow
RootNavigation.Loaded += OnRootNavigationLoaded;
}
+ internal void UpdatePendingIndicator(bool hasPending)
+ {
+ AppTitleText.Text = hasPending ? "optimizerDuck*" : "optimizerDuck";
+ Title = hasPending ? "optimizerDuck*" : "optimizerDuck";
+ }
+
private async void OnRootNavigationLoaded(object sender, RoutedEventArgs e)
{
RootNavigation.Loaded -= OnRootNavigationLoaded;