BLOG.CSHARPHELPER.COM: Randomly change the desktop image in C#
Randomly change the desktop image in C#
The example Set the Windows desktop background picture in C# shows how to display an image on the desktop. This example periodically changes the desktop background to a randomly selected image file picked from a directory.
This example demonstrates several useful techniques including:
The program uses a Timer named tmrNewImage to periodically change the desktop image. The following code shows the Timer's Tick event handler and the ChangeDesktopPicture method that it invokes.
// Display a random image.
private Random Rand = new Random();
private void tmrNewImage_Tick(object sender, EventArgs e)
{
ChangeDesktopPicture();
}
// Display a random image.
private void ChangeDesktopPicture()
{
// Repeat until we succeed or run out of files.
for (; ; )
{
// Pick a random image.
int file_num = Rand.Next(FileNames.Count);
// Try to use that image.
try
{
DisplayPicture(FileNames[file_num], chkUpdateRegistry.Checked);
break;
}
catch
{
// This file doesn't work. Remove it from the list.
FileNames.RemoveAt(file_num);
// If there are no more files, stop trying.
if (FileNames.Count == 0)
{
tmrNewImage.Enabled = false;
break;
}
}
}
}
The ChangeDesktopPicture method display a random picture taken from the FileNames list. The code does its work inside an infinite loop so it can continue until it succeeds. Inside the loop the code picks a random number between 0 and one less than the number of items in the FileNames list. That gives the program the index of one of the items in the list.
Next the code calls the DisplayPicture method to display the picture on the desktop. If the method succeeds, the code breaks out of the infinite loop.
If there is an error displaying the picture, possibly because the file is corrupted or does not have a valid graphic file format, the catch statements execute. The code removes the file from the FileNames list so it won't try to load that file again in the future. If there are no files left in the list, the program disables thue tmrNewImage Timer control and exits the infinite loop.
For more details about how the program works, download the example.
Comments