Saturday, June 3, 2017

Changing the desktop background color with PowerShell

There is a Registry value under HKCU\Control Panel\Colors to control the background color of the desktop, but writing that value doesn't change the current desktop immediately. For a program trying to update the color, the SetSysColors Windows function is the proper way. That's not so easy to handle from the command line, though.

Fortunately, PowerShell can compile and run C# code, which can use P/Invoke to run native Windows functions. This one-liner does the job of defining a type to invoke SetSysColors:
add-type -typedefinition "using System;`n using System.Runtime.InteropServices;`n public class PInvoke { [DllImport(`"user32.dll`")] public static extern bool SetSysColors(int cElements, int[] lpaElements, int[] lpaRgbValues); }"

That function takes a count and then two arrays of that length, one with setting IDs and one with their values. We're only interested in one, the desktop background color (1). The value is the new color in 0xRRGGBB format.

[PInvoke]::SetSysColors(1, @(1), @(0xAA40C0))

This doesn't affect the Registry, so if you want the change to stick, you need to also write the new data to Registry yourself.

Based on my Super User answer.

No comments:

Post a Comment