views:

1586

answers:

2

How can I change the desktop wallpaper using C# Code?

+14  A: 

Here's a class yanked from an app I wrote a year or two ago:

public sealed class Wallpaper
{
    Wallpaper() { }

    const int SPI_SETDESKWALLPAPER = 20;
    const int SPIF_UPDATEINIFILE = 0x01;
    const int SPIF_SENDWININICHANGE = 0x02;

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

    public enum Style : int
    {
        Tiled,
        Centered,
        Stretched
    }

    public static void Set(Uri uri, Style style)
    {
        System.IO.Stream s = new System.Net.WebClient().OpenRead(uri.ToString());

        System.Drawing.Image img = System.Drawing.Image.FromStream(s);
        string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
        img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);

        RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
        if (style == Style.Stretched)
        {
            key.SetValue(@"WallpaperStyle", 2.ToString());
            key.SetValue(@"TileWallpaper", 0.ToString());
        }

        if (style == Style.Centered)
        {
            key.SetValue(@"WallpaperStyle", 1.ToString());
            key.SetValue(@"TileWallpaper", 0.ToString());
        }

        if (style == Style.Tiled)
        {
            key.SetValue(@"WallpaperStyle", 1.ToString());
            key.SetValue(@"TileWallpaper", 1.ToString());
        }

        SystemParametersInfo(SPI_SETDESKWALLPAPER,
            0,
            tempPath,
            SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
    }
}

I havent tested it extensively, so use at your own risk.

Neil N
This will only set BMP files. If I want to set a JPEG what is the method?
Sauron
Not sure if windows support jpeg as wallpaper... it convert other images into bmp before setting up as wallpaper (correct me if im wrong) if that is the case you have to do the conversion in your code
Umair Ahmed
I've been using this for jpegs just fine. Just because its called a bmp in the code above does not limit it. it will *probably* work for pngs and gifs as well as others, but I havent verified that.
Neil N
the above code takes a jpg (when passed to the set function) and saves it as a temp bmp, then sets that. When set again.. its just overwrites that temp bmp with the new one.
Neil N
A: 

Windows keeps such settings in registry.. its only about changing few registry keys... see Neil's code

Umair Ahmed