BLOG.CSHARPHELPER.COM: Set the Windows desktop background picture in C#
Set the Windows desktop background picture in C#
First you must manually set the system to display a background picture. Then this program can change it. (You could probably set it to display a picture in the code but this program is leading to one whose purpose is to randomly changes the background picture not to reconfigure the system.)
The following DisplayPicture method sets the desktop's picture.
// Display the file on the desktop.
private void DisplayPicture(string file_name, bool update_registry)
{
try
{
// See if the file is a bitmap or jpg.
if (!file_name.ToLower().EndsWith(".bmp") &&
!file_name.ToLower().EndsWith(".jpg"))
{
// Load the file.
Bitmap bm = new Bitmap(file_name);
// Save the image into a temporary bitmap file.
string temp_file = Path.GetTempPath() + "\\backer_temp.bmp";
bm.Save(temp_file, ImageFormat.Bmp);
file_name = temp_file;
}
// Set the desktop background to this file.
if (update_registry)
{
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0,
file_name, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
else
{
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0,
file_name, 0);
}
}
catch (Exception ex)
{
MessageBox.Show("Error displaying picture " + file_name + ".\n" +
ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
The program uses the SystemParametersInfo API function to set the desktop picture. Unfortunately that function can only set the picture to the contents of a bitmap or JPEG file so the code first determines whether the indicated file has one of those formats. If the file is in some other format, the program loads the file and then saves it as a bitmap file in the system's temporary file directory.
Next the program calls the SystemParametersInfo function, passing it the SPI_SETDESKWALLPAPER command and the name of the original or temporary file.
The final parameter to SystemParametersInfo can indicate whether the function should modify the Registry to make the new picture permanent. If the user checks the Update Registry checkbox, the program uses SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE for the final parameter so the change is permanent and you will see the new image if you log out or reboot.
If the checkbox is unchecked, the program uses 0 for the final parameter and the picture is temporary. If you log out or reboot, or perform certain other actions that reset the desktop such as opening the Personalize/Desktop Background applet, the picture resets to its original value.
Comments