Search code examples
c#windowswinapitaskbar

Taskbar Color Reverts When Changing Color Using SetWindowCompositionAttribute in WinUI3


I am encountering an issue with the taskbar color on Windows. When I change the taskbar color using the SetWindowCompositionAttribute method, the color initially changes as expected. However, as soon as I click the 'Start' button, the taskbar color reverts to the default color specified by the Windows settings.

Steps to Reproduce:

  1. Change the taskbar color using SetWindowCompositionAttribute.
  2. Observe the taskbar color change.
  3. Click the 'Start' button.
  4. Notice the taskbar color reverting to the Windows default color.

Expected Behavior: The taskbar color should remain as set by SetWindowCompositionAttribute, even after interacting with the 'Start' button.

Actual Behavior: The taskbar color reverts to the default Windows settings when the 'Start' button is clicked.

Code Sample:

public static void SetTaskbarColor(Color color)
{
    var accentPolicy = default(User32Interop.AccentPolicy);

    accentPolicy.Color = color.ToAbgr();
    accentPolicy.AccentState = 2;
    accentPolicy.Flags = 2;

    var data = default(User32Interop.Windowcompositionattribdata);

    data.Attribute = User32Interop.WindowCompositionAttribute.WcaAccentPolicy;
    data.SizeOfData = Marshal.SizeOf(typeof(User32Interop.AccentPolicy));
    data.Data = Marshal.AllocHGlobal(data.SizeOfData);

    Marshal.StructureToPtr(accentPolicy, data.Data, false);

    var taskbarHandle = User32Interop.FindWindow("Shell_TrayWnd", null);

    var secondaryTaskbarHandle = User32Interop.FindWindow("Shell_SecondaryTrayWnd", null);

    if (taskbarHandle != nint.Zero)
    {
        User32Interop.SetWindowCompositionAttribute(taskbarHandle, ref data);
    }

    if (secondaryTaskbarHandle != nint.Zero)
    {
        User32Interop.SetWindowCompositionAttribute(secondaryTaskbarHandle, ref data);
    }

    Marshal.FreeHGlobal(data.Data);
}

Solution

  • Answer to this question is on this thread: https://learn.microsoft.com/en-us/answers/questions/2046028/taskbar-color-reverts-when-changing-color-using-se

    Solution was to add change of taskbar's color to Timer or Thread, which will repeatedly refresh it