Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

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 4.6 with 21 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.

by InASimpleMess on Friday, August 7th 2009 at 01:30 AM

I'm in office right now, and here IT guys had disabled the function to change destop Background. So a user will not see the Desktop Tab whenever they right-click on Windows XP professional's desktop.

In this scenario another interesting thing for u is that they have altered the basic/default location of wallpaper as well as its filename also.

Which means that wallpaper will always be selected from dafault location of "C:\Documents and Settings\\Local Settings\Application Data\Microsoft" and its filename should be "wallpaper.bmp" only.

In this situation... I would luv to make u think about a solution to change the wallpaper :)

by InASimpleMess on Friday, August 7th 2009 at 01:48 AM

I forgot to mention that I really liked the way this TuT had been written, its excellent.

When I logout... the desktop background is changed, means it had worked. But the current user's background id still not changed.

Whenever the user will login back into the network... the current user's background will be reset back to what had been done my IT fellars.

Now u may please proceed to test :)

by Amit on Wednesday, January 6th 2010 at 11:43 AM

Good tutorial to learn new thing.Continued the good work.

Thanks,
Amit Pandey

by dsf on Wednesday, January 13th 2010 at 06:56 AM

sd

by Ankit Bhatt on Tuesday, July 13th 2010 at 02:58 AM

Thanks a lot for this Project....


Really very helpful.....

Can u give me this in .VBS format....

Means VB script we can run directly...

Anyways Many thanks.....

Carryon

by Ankit Bhatt on Tuesday, July 13th 2010 at 02:58 AM

Thanks a lot for this Project....


Really very helpful.....

Can u give me this in .VBS format....

Means VB script we can run directly...

Anyways Many thanks.....

Carryon

by Alex on Wednesday, August 18th 2010 at 06:49 AM

The data type of the WallpaperStyle and TileWallpaper should be string. If they are saved to the registry as int [or any other number format] it does not work.

Here's my modification of the code which works for me:
____________________________________________
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;
//determine the option the user has selected
string tileStyle = "0";
string wallStyle = "0";
switch (ddlStyle.SelectedIndex)
{
case 0: //stretch
tileStyle = "0";
wallStyle = "2";
break;
case 1: //center
tileStyle = "0";
wallStyle = "0";
break;
default:
tileStyle = "1";
wallStyle = "0";
break;
}
// Pass the file path, and two options to specify the wallpaper style
SetWallpaper(openGraphic.FileName, wallStyle, tileStyle);
}
}

private void SetWallpaper(string WallpaperLocation, string WallpaperStyle, string TileWallpaper)
{
// 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);
//set the wallpaper's location
rkWallPaper.SetValue("Wallpaper", WallpaperLocation);
// Sets the wallpaper style (tile, center, stretch)
rkWallPaper.SetValue("WallpaperStyle", WallpaperStyle);
rkWallPaper.SetValue("TileWallpaper", TileWallpaper);
//close the registry key
rkWallPaper.Close();
// Have the computer update the wallpaper
SystemParametersInfo(20, 0, WallpaperLocation, 0x01 | 0x02);
}
________________________________________

by notIndian on Sunday, August 29th 2010 at 12:36 PM

indians are stupid!!! >.

by Arminder on Wednesday, September 1st 2010 at 03:52 AM

gud tutorial given by u


but i have problem relating this i m convert html into image format i.e bmp and then use this code to set the desktop background but its not working
but if i right click the image and then select set as i backgroud it work ....plz help me

by atul on Thursday, October 7th 2010 at 06:24 AM

very nice... i am looking for solution to any type of image file on xp

by Amol on Monday, November 1st 2010 at 01:20 AM

Hi Its a very good tutorial and working fine for me..
but what i want... i want to set all my office computers wallpaper when i will set my own wallpaper its the same for all computers..
so please help me how to do the same...

by Jon on Thursday, November 4th 2010 at 04:46 PM

I'm not seeing how to adjust the code to maintain aspect ratio, can anyone help?

by Christopher Trew on Wednesday, January 19th 2011 at 03:56 PM

Thanks for the great article. Exactly what I was looking for.

by thank you quotes on Saturday, August 13th 2011 at 03:22 PM

Nicely presented info in this mercantilism, I depute to know this kindhearted of whatsis. The wellborn of knowledge is satisfying and the morpheme is eligible. Thanks for the option.

by romantic birthday wishes on Tuesday, August 16th 2011 at 01:48 AM

I'm in office right now, and here IT guys had disabled the function to change destop Background. So a user will not see the Desktop Tab whenever they right-click on Windows XP professional's desktop.

by Testking CISSP on Thursday, August 25th 2011 at 01:31 AM

Nice information in this commercial, I know that members do a good heart. Knowledge of well-born is satisfactory and the morpheme are eligible. Thanks for the option.

by garage shoes on Thursday, August 25th 2011 at 01:37 AM

Hello!

I just want to know how I can set my own wallpaper on the screen and you can not pull or change, except me.can help with that.

by free dating sites on Sunday, November 20th 2011 at 07:00 AM

This is one of the most incredible blogs Ive read in a very long time. The amount of information in here is stunning, like you practically wrote the book on the subject. Your blog is great for anyone who wants to understand this subject more. Great stuff; please keep it up!

by GenF20 Plus on Monday, December 19th 2011 at 06:01 PM

Your personal know-how and kindness in maneuvering every part was tremendous. I am not sure what I would've done if I hadn't encountered such a solution like this. I'm able to at this time look ahead to my future. Thanks a lot so much for the specialized and result oriented help. I won't hesitate to endorse the blog to anybody who desires assistance on this topic.

by GenFX on Monday, December 19th 2011 at 06:04 PM

Your personal know-how and kindness in maneuvering every part was tremendous. I am not sure what I would've done if I hadn't encountered such a solution like this. I'm able to at this time look ahead to my future. Thanks a lot so much for the specialized and result oriented help. I won't hesitate to endorse the blog to anybody who desires assistance on this topic.

by Teeth Whitening Reviews on Tuesday, December 20th 2011 at 01:40 AM

I truly wanted to write a quick message to thank you for some of the splendid points you are showing at this website. My long internet investigation has at the end been compensated with sensible facts and techniques to share with my family and friends.

by Human Growth Hormone on Tuesday, December 20th 2011 at 01:40 AM

I truly wanted to write a quick message to thank you for some of the splendid points you are showing at this website. My long internet investigation has at the end been compensated with sensible facts and techniques to share with my family and friends.

by Best Diet Pills on Tuesday, December 20th 2011 at 01:46 AM

I would believe that we visitors are truly blessed to dwell in a wonderful network with many wonderful professionals with very beneficial hints. I feel extremely privileged to have seen the web pages and look forward to many more pleasurable times reading here. Thank you once again for everything.

by HGH Advanced on Tuesday, December 20th 2011 at 01:53 AM

I would believe that we visitors are truly blessed to dwell in a wonderful network with many wonderful professionals with very beneficial hints. I feel extremely privileged to have seen the web pages and look forward to many more pleasurable times reading here. Thank you once again for everything.

by Dental White on Tuesday, December 20th 2011 at 01:56 AM


Thanks so much for providing individuals with an extremely remarkable possiblity to read critical reviews from this web site. It is always so beneficial plus jam-packed with a great time for me personally and my office friends to search the blog at the least three times in one week to see the fresh secrets you will have.

by Pure Acai Berry Max on Tuesday, December 20th 2011 at 01:59 AM


Thanks so much for providing individuals with an extremely remarkable possiblity to read critical reviews from this web site. It is always so beneficial plus jam-packed with a great time for me personally and my office friends to search the blog at the least three times in one week to see the fresh secrets you will have.

by Ultimate Maqui Berry on Tuesday, December 20th 2011 at 02:02 AM

I am just always happy with your good tips and hints served by you. Some 1 areas in this article are undeniably the finest I've had.

by Proactol Plus on Tuesday, December 20th 2011 at 02:04 AM

I am just always happy with your good tips and hints served by you. Some 1 areas in this article are undeniably the finest I've had.

by Provacyl on Tuesday, December 20th 2011 at 02:09 AM

I am just always happy with your good tips and hints served by you. Some 1 areas in this article are undeniably the finest I've had.

by Nuratrim on Tuesday, December 20th 2011 at 02:13 AM

Thanks a lot for providing individuals with remarkably special possiblity to read critical reviews from this web site. It can be very kind plus packed with a great time for me personally and my office mates to visit your site no less than three times weekly to study the newest tips you have.

by Capsiplex on Tuesday, December 20th 2011 at 02:21 AM

Thanks a lot for providing individuals with remarkably special possiblity to read critical reviews from this web site. It can be very kind plus packed with a great time for me personally and my office mates to visit your site no less than three times weekly to study the newest tips you have.

by gd poker online on Sunday, January 22nd 2012 at 10:52 AM

I intended to post you that little word just to say thank you as before about the lovely strategies you've documented above. This is really incredibly open-handed of you giving easily just what many individuals would've distributed as an electronic book to help with making some profit on their own, specifically considering that you might well have done it if you wanted. Those secrets also served to become good way to know that most people have a similar interest really like my personal own to learn a little more on the subject of this matter. Certainly there are thousands of more enjoyable opportunities ahead for people who check out your website.

by Jan Baptysta on Tuesday, January 24th 2012 at 05:51 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by remote access software ip on Tuesday, October 2nd 2012 at 02:38 AM

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


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 >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources