Randomly change the desktop picture in C#

[desktop picture]

The example Set the Windows desktop picture in C# shows how to display an image on the desktop. This example periodically changes the desktop picture to a randomly selected image file picked from a directory.

Note that recent versions of Windows have that ability built in. You can enhance this example to provide other features, such as picking files from multiple directories, but if you just want a slide show, it will be easier to use Window’s features.

This example uses techniques described in the following posts:

The program uses a Timer named tmrNewImage to periodically change the desktop image. The following code shows the Timer component’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 displays 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 name from the FileNames list. It then 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 block executes. 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 the tmrNewImage Timer and exits the infinite loop.

For more details about how the program works, download the example and take a look at the code.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in API, graphics, image processing, interoperability, system and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *