Geekpedia Programming Tutorials






Setting and Retrieving the Desktop Wallpaper

In this tutorial you will learn how to interact with the unmanaged Windows API using C# in order to set the desktop background (wallpaper), and use the registry to retrieve the current wallpaper.

On Monday, June 4th 2007 at 01:34 AM
By Andrew Pociu (View Profile)
*****   (Rated 5 with 6 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

While Windows Vista offers quite a nice way of setting the desktop background, how do we do about writting our own code for changing the wallpaper? This tutorial will show you how to use the unmanaged SystemParametersInfo() function in order to change the background picture for all of the latest Windows operating systems, including Windows 2000, XP, Server 2003, Server 2008 and Vista. However, it is important to note that only with Windows Vista you will be able to set a JPEG, PNG, GIF and other such pictures as the desktop background. With Windows XP and other versions of Windows the code only works with Bitmap (BMP) files.

Vista Desktop Background

Start by creating a new project in Visual Studio 2005 and on the form drop a PictureBox picThumbnail, a DropDownList ddlStyle containing the values "Fit To Screen", "Center", "Tile", a Button btnSet and finally an OpenFileDialog named openGraphic. The drop-down list is not being used in this tutorial, however you could have it set different combinations for the WallpaperStyle and TileWallpaper registry values you'll learn about later, in order to have the desktop background in tiles (repeat to fill the screen), stretch, maintain aspect ratio, center, and so on.

Wallpaper Form

Now switch to code view and add the following using statements:


using Microsoft.Win32;

using System.Runtime.InteropServices;


Microsoft.Win32 is used for accessing the registry, while System.Runtime.InteropServices is used for accessing the unmanaged user32.dll.

Next comes the preparation of the unmanaged function SystemParametersInfo() - this should be located at the top of the class definition:


[DllImport("user32.dll", CharSet = CharSet.Auto)]

static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);


First thing is to retrieve the current desktop wallpaper, and to do that we don't need to use a function, but simply read a value in the Windows registry. Let's create the method for that:


private string GetCurrentWallpaper()

{

    // The current wallpaper path is stored in the registry at HKEY_CURRENT_USER\\Control Panel\\Desktop\\WallPaper

    RegistryKey rkWallPaper = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", false);

    string WallpaperPath = rkWallPaper.GetValue("WallPaper").ToString();

    rkWallPaper.Close();

    // Return the current wallpaper path

    return WallpaperPath;

}


Next comes the definition of the method that actually sets the wallpaper, the main purpose of this tutorial. And it's only a few lines of code:


private void SetWallpaper(string WallpaperLocation, int WallpaperStyle, int TileWallpaper)

{

    // Sets the actual wallpaper

    SystemParametersInfo(20, 0, WallpaperLocation, 0x01 | 0x02);

    // Set the wallpaper style to streched (can be changed to tile, center, maintain aspect ratio, etc.

    RegistryKey rkWallPaper = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);

    // Sets the wallpaper style

    rkWallPaper.SetValue("WallpaperStyle", WallpaperStyle);

    // Whether or not this wallpaper will be displayed as a tile

    rkWallPaper.SetValue("TileWallpaper", TileWallpaper);

    rkWallPaper.Close();

}


As you can see there are three parameters, one which is the path of the wallpaper, and the other two in different combinations can set the wallpaper as tile, stretch, centered, etc.

Now that we have the two methods in place, we can set the PictureBox to the current desktop background:


private void Form1_Load(object sender, EventArgs e)

{

    // Select the first value of the dropdown by default

    ddlStyle.SelectedIndex = 0;

    // The PictureBox image will fit but keep its aspect ratio

    picThumbnail.SizeMode = PictureBoxSizeMode.Zoom;

    // Show the current wallpaper

    picThumbnail.ImageLocation = GetCurrentWallpaper();

}


And now the final code to add is in the Click event of the btnSet button. This shows the OpenFileDialog so that the user can select a wallpaper, calls the background setting method and sets the PictureBox picture to a thumbnail of the newly picked wallpaper:


private void btnSet_Click(object sender, EventArgs e)

{

    if (openGraphic.ShowDialog() == DialogResult.OK)

    {

        // Preview the wallpaper in a PictureBox

        picThumbnail.ImageLocation = openGraphic.FileName;

        // Fit the PictureBox

        picThumbnail.SizeMode = PictureBoxSizeMode.Zoom;

        // Pass the file path, and two options to specify the wallpaper style

        SetWallpaper(openGraphic.FileName, 2, 0);

    }

}


That's all folks! And here's a photo from Central Park being set as the desktop wallpaper:

Desktop Wallpaper
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Pete Houston on Monday, June 4th 2007 at 12:20 PM

Very nice ! You\'ve done a good job. I always loop up for all the new tutorials form you.
Such a wonderful page !
Keep going on...

by }{ombr3 on Wednesday, June 6th 2007 at 10:04 AM

this one doesn't work...
first of all i changed the code and tried other options to get it run, but it still doesn't work!
when i want to set the new wallpaper, my desktop wallpaper is always dark blue (i'm using windows xp service pack 2)
---
1 bug i detected is at the RegistryKey.SetValue method where you optional can put a RegistryKeyKind parameter
---
from other sources i found out that the API call looks like that:
SystemParametersInfo(20, 1, WallpaperLocation, 0x2);

but that even didn't help -.-
---
before that i sometimes have dealt with unmanaged functions... that always went good...

by Andrei Pociu on Wednesday, June 6th 2007 at 11:31 AM

The code has only been tested with Windows Vista. It works with Windows 2000, 2003 and XP as well, but only with Windows Bitmap files (BMP). It won't work with PNG, JPEG, GIF, etc. as it does on Windows Vista. I'm adding this information to the tutorial.

by }{ombr3 on Monday, June 11th 2007 at 05:43 AM

rrrrrrright... with BMP files it works now ;)

by Jerry on Saturday, June 30th 2007 at 07:46 AM

Hi, it is possible to set an hmtl desktop using this code?

by suhas on Thursday, August 23rd 2007 at 07:30 AM

Sir,

I want to learn C++ online and want to be capable of creating programs for graphics.

how should i proceed to be effective in my goals

by Robert Manahan on Wednesday, October 31st 2007 at 12:05 PM

in XP, there was a 1 liner using user32.dll to refresh the wallpaper after a change to the registry...is that possible in vista?

by vipul patel on Thursday, November 8th 2007 at 02:58 PM

when i go to control panel then personalise to put backgound wallpaperon. the part that says backgound as disappered and the background is black at the moment how do i get it back on

by Gary Dent on Friday, December 14th 2007 at 12:01 PM

when i go to control panel then personalise to put backgound wallpaperon. the part that says backgound as disappered and the background is black at the moment how do i get it back on

by SoLoGHoST on Friday, June 20th 2008 at 02:13 AM

This code does not retrieve the wallpaper for a solid color wallpaper. Where in the registry can I get the color of the wallpaper if it is a solid black, white, red, green, etc... since when solid colors are chosen, the wallpaper value is "" (blank). Please help...

by Mazin on Friday, July 18th 2008 at 06:03 AM

Hi the process worked fine for me but when I try to make it into a windows service which triggers the event every 10 minutes The SystemParametersInfo(20,1, location, 2|1) returns 0 and the wallpaper doesnt change.

I tried using the local system environment and using the user environment.
Could you please help me sort it out.

by Mazin on Friday, July 18th 2008 at 06:03 AM

Hi the process worked fine for me but when I try to make it into a windows service which triggers the event every 10 minutes The SystemParametersInfo(20,1, location, 2|1) returns 0 and the wallpaper doesnt change.

I tried using the local system environment and using the user environment.
Could you please help me sort it out.

by apeng on Wednesday, July 30th 2008 at 09:56 AM

hi!i just wanna know how can i set up my own wallpaper on my screen without anyone can discard or change it except me.can you help for this.

by Finch on Wednesday, September 24th 2008 at 03:48 AM

Hey, thanks for the tutorial. It taught me exaclty what i wanted to know.

I have modified your program into one that cycles through an array of images, changing the desktop image at user defined time intervals.

The problem i am having however is that only certain images work. I am using windows XP and yes, i am only using .bmp files. As i say, only some of the images work, ones that do not work simply turn the desktop a solid blue colour untill the next working image comes and replaces it.

Any help would be much appreciated. Thank you

by Andy Polshaw on Friday, November 7th 2008 at 06:27 AM

You wouldn't believe how long it took to find a method in code to refresh the registry settings. Executing RunDLL32.exe (either from code or manually) just didn't do it.

Thanks very much! All I have to tie down now are the permissions issues with accessing unmanaged code through a remoted/WCF component...

by Prajeesh Prabhakar on Monday, February 9th 2009 at 09:39 PM

Thanks for ur tutorial

by Yossu on Sunday, March 22nd 2009 at 01:06 PM

Did anyone sort out how to get this to work from a Windows service? I have it working fine from a Forms application, but when I copy the same code into a service, the wallpaper isn't changed.

Anyone know? Thanks,
Yossu

by Yossu on Sunday, March 22nd 2009 at 01:09 PM

Oops, right after posting I found the answer.

In case it helps anyone, you can't do this from a service! See this discussion for more details...

http://www.codeproject.com/script/Forums/View.aspx?fid=1649

by rajesh on Monday, May 11th 2009 at 07:00 AM

it is not working properly

by rajesh on Monday, May 11th 2009 at 07:00 AM

it is not working properly

by Domino on Monday, May 25th 2009 at 03:01 PM

Bad code. You should use special Windows interfaces instead of manual editing the registry.


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons