It’s about a week that I’m working on an advertising application which manages customer’s advertising programs. One of the cool features that my customer requested was to change user’s desktop wallpaper into a specific photo or add some advertising notes to the current wallpaper.
So I started developing this application and faced something: “How to programmatically change Windows Desktop Wallpaper?”
As you know, to change anything in Windows, you have to make use of Windows APIs. This one is the same. In order to change anything in Control Panel, There is an API function, named “SystemParametersInfo” :
The SystemParametersInfo function retrieves or sets the value of one of the system-wide parameters. This function can also update the user profile while setting a parameter.
How it works:
First of all you need to import System.Runtime.InteropServices namespace. This namespace enables you to import your favorite Windows API function library.
Note that SystemParametersInfo function is in User32.dll library.
To import a Windows API library in C#, it’s necessary to use “DLLImport” attribute:
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int SystemParametersInfo(int uAction,
int uParam,
string lpvParam,
int fuWinIni);
Now you have the function, so you have to use it somewhere:
string path = @"C:\Users\Public\Pictures\Sample Pictures\Desert.bmp";
const int SPI_SETDESKWALLPAPER = 20;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;
SystemParametersInfo(SPI_SETDESKWALLPAPER,
0,
path,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
Note that, the file you specify to be the wallpaper must be in Bitmap format. If you have JPEG, PNG, etc. files, you have to convert it to Bitmap, save it in a temp folder and then set it as Windows wallpaper.