How to set Bing wallpaper as your desktop wallpaper

May 08, 2014 by Anuraj

.Net .Net 4.0 CodeProject Win 32 API Windows Forms Windows Phone

This post is about setting Bing wallpaper as your desktop wallpaper using C# and Windows Forms. Bing.com is famous for having some nice pictures as wallpaper, updated on daily basis. The Bing Desktop application comes with same feature. Here is the code snippet, which has two parts one, download the wallpaper image from bing.com and set it as wallpaper using WIN32 APIs.

The URL for getting wallpaper is used by bing WP7 application. http://appserver.m.bing.net/BackgroundImageService/TodayImageService.svc/GetTodayImage?dateOffset=0&urlEncodeHeaders=true&osName=wince&osVersion=7.10&orientation=480x800&deviceName=WP7Device&mkt=en-US&AppId=1

In the URL, you can change the orientation to 1024×768, landscape mode in Windows Phone to get the wallpaper. And the mkt parameter specifies the region, I am keep it as en-US. The following snippet will download the wallpaper and save it in the Temp folder as wallpaper.bmp. The SetWallpaper function will set the wallpaper.bmp as desktop wallpaper using Win32 API.

WebClient webClient = new WebClient();
webClient.OpenReadCompleted += (o, ev) =>
{
    if (ev.Error == null)
    {
        var wallpaper = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
        using (var bitmap = Bitmap.FromStream(ev.Result))
        {
            bitmap.Save(wallpaper, ImageFormat.Bmp);
            SetWallpaper(wallpaper);
        }
    }
};

webClient.OpenReadAsync(new Uri(bingserviceUrl));

Here is the SetWallpaper method

private static void SetWallpaper(string wallpaper)
{
    RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
    key.SetValue(@"WallpaperStyle", 2.ToString());
    key.SetValue(@"TileWallpaper", 0.ToString());

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

You require following WIN32 API declarations as well.

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);

In the SetWallpaper function, I am setting the wallpaper picture position as Stretched. You can change this by changing the WallpaperStyle and TileWallpaper values.

Picture PositionWallpaperStyleTileWallpaper
Stretched20
Centered10
Tiled11
Fit*60
Fill*100
* - Windows 7 and later

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub