How do I set the desktop background on Windows from a script?

Solution 1:

This does change the background via command line. Just save this as a bat file. Use bmp or you will have to refresh. Also sets the wallpaper to be stretched. If you take out the wallpaperstyle line it will automatically be centered.

@echo off
reg add "HKCU\control panel\desktop" /v wallpaper /t REG_SZ /d "" /f 
reg add "HKCU\control panel\desktop" /v wallpaper /t REG_SZ /d "C:\[LOCATION OF WALLPAPER HERE]" /f 
reg delete "HKCU\Software\Microsoft\Internet Explorer\Desktop\General" /v WallpaperStyle /f
reg add "HKCU\control panel\desktop" /v WallpaperStyle /t REG_SZ /d 2 /f
RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters 
exit

Solution 2:

I think that once you modify the wallpaper setting in the registry, you simply need to run

RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters 

from the command line and the changes should take effect. You need to make sure that your image is a bmp file.

In fact, I just tried this by creating a desktop sized bmp file that was all red. I changed the //HKCU/control panel/desktop/wallpaper key to contain the full pathname to this bitmap. I ran the above command from the command line and the desktop changed to the red bmp that I just created

Solution 3:

Here is one option. Create a small Console App with a SharpDevelop. Put this code into Programs.cs. I call the app "CWP"; Change wallpaper. It takes just one parameter on command line: the file name. Tested on Windows 7 Ultimate 64-bit with .bmp -file.

    /*
     * Created by SharpDevelop.
     * Date: 21.9.2012
     * Time: 16:13
     */
    using System;
    using System.Data;
    using System.Text;
    using System.Runtime.InteropServices;

    namespace cwp
    {

       class Program
        {
           [DllImport("user32.dll")]
           public static extern Int32 SystemParametersInfo(
               UInt32 action, UInt32 uParam, String vParam, UInt32 winIni);

            public static readonly UInt32 SPI_SETDESKWALLPAPER  = 0x14;
            public static readonly UInt32 SPIF_UPDATEINIFILE    = 0x01;
            public static readonly UInt32 SPIF_SENDWININICHANGE = 0x02;

            public static void SetWallpaper(String path)
            {
                Console.WriteLine("Setting wallpaper to '" + path + "'");
                SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path,
                    SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
            }

            public static void Main(string[] args)
            {
                if (args.Length >= 1)
                {
                    SetWallpaper( args[0] );
                }
            }
        }
    }

Solution 4:

this isn't as cool as actually spending time writing code, but there's a pretty useful system util called bginfo that embeds info into the desktop's background. it's fairly configurable with all sorts of command-line options. no, i didn't write it.