Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Automated Desktop Background Changer

0.00/5 (No votes)
15 Dec 2007 1  
This project will show you how to make a program that randomly chooses a background image when you log on, and either lets you simply select a background, or randomly chooses one for you every minute to an hour.

Introduction

Ever been stuck trying to find the right image to use as your background? Well, look no further. This project will show you how to make a program that randomly chooses a background image when you log on, and either lets you simply select a background, or randomly chooses one for you every minute to an hour. Also this project includes instructions on how to convert an image to BMP format.

Background

A full and well grounded knowledge of VB 2005 and greater.

Using the Code

Sample Image

First start a new project and call it "Random Desktop".
Name the Form frmRD. Now create a new class and call it Wallpaper.vb, also create a new Form called frmConverter.

Okay good. Now on frmRD, place and name the following attributes to look like the picture shown above.

  • Picturebox Preview
  • Combobox styleComboBox
  • Button btnConverter
  • Button btnPlay
  • Button btnNext (the font is Marlett, then to type arrows, type 44)
  • Button btnRefresh
  • Button btnBackround
  • Listbox PictureSelection
  • NumericUpDown ImageTime
  • Checkbox CountdownSwitch

The code for frmRD goes like this:

Public Class frmRD

'Variables
    Dim FILE As String
    Dim Delete As Byte
    Dim DIR As String = My.Computer.FileSystem.SpecialDirectories.MyPictures & _
        "\RandomBG\"
    Dim SS As Byte = 0
    Dim IntervalSS As Integer
    Dim RandomImage As Integer
    Dim CurrentImage As Integer
    Dim Max As Integer

    Private Sub frmRD_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles MyBase.Load

'On Load, find all files in the My Pictures\RandomBG\ folder
    For Each File As String In My.Computer.FileSystem.GetFiles_
        (My.Computer.FileSystem.SpecialDirectories.MyPictures & "\RandomBG\")
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next

        styleComboBox.DataSource = System.Enum.GetNames(GetType(Wallpaper.Style))
        styleComboBox.SelectedIndex = 2

'On load, randomly select a background image from the My Pictures\RandomBG\ folder
    Try
            Max = PictureSelection.Items.Count

            RandomImage = GetRandomNumber(1, Max)

            PictureSelection.SelectedIndex = RandomImage - 1

            FILE = PictureSelection.Text

            Preview.Image = Image.FromFile_
                (My.Computer.FileSystem.SpecialDirectories.MyPictures & _
                "\RandomBG\" & FILE)

            Dim w As Wallpaper = New Wallpaper()
            w.SetWallpaper(My.Computer.FileSystem.SpecialDirectories.MyPictures & _
                "\RandomBG\" & FILE, CType(System.Enum.Parse_
                (GetType(Wallpaper.Style), styleComboBox.Text), Wallpaper.Style))
        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub PictureSelection_MouseClick(ByVal sender As System.Object, ByVal e _
        As System.Windows.Forms.MouseEventArgs) Handles PictureSelection.MouseClick

'Preview an image by clicking it's name in the listbox
    Try
            FILE = PictureSelection.Text

            Preview.Image = Image.FromFile(DIR & FILE)
        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub PictureSelection_MouseDoubleClick(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs) _
        Handles PictureSelection.MouseDoubleClick

'Remove a file from the list by double clicking it
    PictureSelection.Items.Remove(PictureSelection.SelectedItem)
    End Sub



    Private Sub btnBackround_Click(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles btnBackround.Click

'Set the currently previewed wallpaper as the background
    Dim w As Wallpaper = New Wallpaper()
        w.SetWallpaper(My.Computer.FileSystem.SpecialDirectories.MyPictures & _
            "\RandomBG\" & FILE, CType(System.Enum.Parse(GetType(Wallpaper.Style), _
            styleComboBox.Text), Wallpaper.Style))

    End Sub


    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles btnRefresh.Click

'Refreshes the listbox, in case new files have been added by the converter
    PictureSelection.Items.Clear()

        For Each File As String In My.Computer.FileSystem.GetFiles(DIR)
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next
    End Sub

'When the GetRandomNumber(min, max) function is called, it chooses a random number 
'from the minimum to the maximum specified
#Region "Random Number Generator"
    Private Function GetRandomNumber(ByVal vnMinimumNumber As Integer, _
        ByVal vnMaximumNumber As Integer)
        Randomize()
        GetRandomNumber = CInt(Int((vnMaximumNumber - vnMinimumNumber + 1) * _
            Rnd() + vnMinimumNumber))
    End Function
#End Region

    Private Sub btnPlay_Click(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles btnPlay.Click

'Sets up the timers, and prepares the Forms vital controls for the auto changer
    If SS = 0 Then
            Counter = ImageTime.Value * 60
            Speed = ImageTime.Value * 60
            IntervalSS = (ImageTime.Value * 60000)
            Slideshow.Interval = IntervalSS
            Countdown.Enabled = True
            Slideshow.Enabled = True
            ImageTime.Enabled = False
            btnBackround.Enabled = False
            styleComboBox.Enabled = False
            btnPlay.Text = "Stop"
            SS = 1
        ElseIf SS = 1 Then
            Slideshow.Enabled = False
            Countdown.Enabled = False
            ImageTime.Enabled = True
            btnBackround.Enabled = True
            styleComboBox.Enabled = True
            btnPlay.Text = "Play"
            SS = 0
        End If
    End Sub

    Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles btnNext.Click

'Randomly skips ahead one image in the sequence, and sets it as the background
    Try
            Max = PictureSelection.Items.Count
            CurrentImage = RandomImage
            RandomImage = GetRandomNumber(1, Max)

            If RandomImage = CurrentImage Then
                Exit Sub
            End If

            PictureSelection.SelectedIndex = RandomImage - 1

            FILE = PictureSelection.Text

            Dim w As Wallpaper = New Wallpaper()
            w.SetWallpaper(DIR & FILE, CType(System.Enum.Parse(GetType(Wallpaper.Style), _
            styleComboBox.Text), Wallpaper.Style))

        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub Slideshow_Tick(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Slideshow.Tick

'Randomly chooses a new image and applies it every pre-determined tick
    Try
            Max = PictureSelection.Items.Count
            CurrentImage = RandomImage
            RandomImage = GetRandomNumber(1, Max)

            If RandomImage = CurrentImage Then
                Exit Sub
            End If

            PictureSelection.SelectedIndex = RandomImage - 1

            FILE = PictureSelection.Text

            Dim w As Wallpaper = New Wallpaper()
            w.SetWallpaper(DIR & FILE, CType(System.Enum.Parse(GetType(Wallpaper.Style), _
            styleComboBox.Text), Wallpaper.Style))

        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles btnConvert.Click

'Runs the conversion form
    frmConverter.Show()
        Me.Hide()
    End Sub

'Variables just for the counter
    Dim Counter As Integer
    Dim Speed As Integer
    Dim Switch As Byte = 0

    Private Sub Countdown_Tick(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Countdown.Tick

'Determines the message when the counter is switched on
    Counter = Counter - 1
        If Switch = 1 Then
            If Counter > 0 Then
                Me.Text = "(" & Counter & " Seconds Remaining)"
            ElseIf Counter = 1 Then
                Me.Text = "(" & Counter & " Second Remaining)"
            ElseIf Counter = 0 Then
                Me.Text = "(" & Counter & " Seconds Remaining)"
                Counter = Speed
            End If
        Else

        End If
    End Sub

    Private Sub CountdownSwitch_CheckedChanged(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles CountdownSwitch.CheckedChanged

'Determines whether the counter is switched on
    If CountdownSwitch.Checked = True Then
            Switch = 1
        Else
            Switch = 0
            Me.Text = " Random Desktop"
        End If
    End Sub
End Class

The code for the Wallpaper class goes like this:

Imports System
Imports System.Runtime.InteropServices
Imports System.Drawing
Imports Microsoft.Win32

Public Class Wallpaper
    Const SPI_SETDESKWALLPAPER As Integer = 20
    Const SPIF_UPDATEINIFILE As Integer = &H1&
    Const SPIF_SENDWININICHANGE As Integer = &H2&

    "user32") /> _
    Public Shared Function SystemParametersInfo(ByVal uAction As Integer, _
        ByVal uParam As Integer, ByVal lpvParam As String, ByVal fuWinIni As Integer) _
            As Integer
    End Function

    Public Enum Style As Integer
        Tiled
        Centered
        Stretched
    End Enum

    Public Sub SetWallpaper(ByVal path As String, ByVal selectedStyle As Style)
        Dim key As RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey_
            ("Control Panel\Desktop", True)

        Select Case selectedStyle
            Case Style.Stretched
                key.SetValue("WallpaperStyle", "2")
                key.SetValue("TileWallpaper", "0")

            Case Style.Centered
                key.SetValue("WallpaperStyle", "1")
                key.SetValue("TileWallpaper", "0")

            Case Style.Tiled
                key.SetValue("WallpaperStyle", "1")
                key.SetValue("TileWallpaper", "1")
        End Select

        SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE _
            Or SPIF_SENDWININICHANGE)
    End Sub
End Class
Sample Image

The reason we need a converter is because Windows XP won't allow you to use any kind of image for the background except a *.bmp. Usually when you select an image as the background, Windows converts it to a *.bmp for you and then uses it.

Now on frmConverter, place and name the following attributes to look like the picture shown above.

  • Picturebox Preview
  • Combobox FileType
  • Button btnConvert
  • Button btnFolder
  • Button btnRefresh
  • Listbox PictureSelection

The code for frmConverter goes like this:

Public Class frmConverter

'Variables for retrieving and saving files
    Dim DIR As String = My.Computer.FileSystem.SpecialDirectories.MyPictures & "\"
    Dim FILE As String

    Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles btnConvert.Click

'Saves the selected image as a .bmp to the My Pictures\RandomBG\ directory
    On Error Resume Next
        Dim d As New System.Drawing.Bitmap(Preview.Image)
        Dim tmp As String = PictureSelection.Text
        tmp = tmp.ToUpper
        If PictureSelection.SelectedIndex < 0 Then
            My.Computer.Audio.Play("C:\Windows\Media\ding.wav")
            Exit Sub
        End If
        tmp = Microsoft.VisualBasic.Replace(UCase(tmp), FileType.Text, "BMP")
        d.Save(My.Computer.FileSystem.SpecialDirectories.MyPictures & _
        "\RandomBG\" & tmp, System.Drawing.Imaging.ImageFormat.Bmp)
        Dim answer As MsgBoxResult
        answer = MsgBox("Are you done converting?", MsgBoxStyle.YesNo)
        If answer = MsgBoxResult.Yes Then
            Me.Close()
        End If
    End Sub

    Private Sub frmConverter_Load(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles MyBase.Load

'On Load, Read all the items in the (Default) My Pictures folder to the listbox
    For Each File As String In My.Computer.FileSystem.GetFiles_
        (My.Computer.FileSystem.SpecialDirectories.MyPictures)
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next
    End Sub

    Private Sub PictureSelection_MouseClick(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs) _
        Handles PictureSelection.MouseClick

'Preview an image for conversion
    Try
            FILE = PictureSelection.Text

            Preview.Image = Image.FromFile(DIR & FILE)
        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub PictureSelection_MouseDoubleClick(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.MouseEventArgs) _
        Handles PictureSelection.MouseDoubleClick

'Double click a file in the listbox to remove it
     PictureSelection.Items.Remove(PictureSelection.SelectedItem)
    End Sub

    Private Sub btnFolder_Click(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles btnFolder.Click

'Select a folder to get images from, (the default is My Pictures)
    FolderBrowser.ShowDialog()
        DIR = FolderBrowser.SelectedPath & "\"

        PictureSelection.Items.Clear()

        For Each File As String In My.Computer.FileSystem.GetFiles(DIR)
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next
    End Sub

    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e _
        As System.EventArgs) Handles btnRefresh.Click

'Refresh the items in the listbox, in case files have been added to the selected folder
    PictureSelection.Items.Clear()

        For Each File As String In My.Computer.FileSystem.GetFiles(DIR)
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next
    End Sub

    Private Sub frmConverter_FormClosing(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.FormClosingEventArgs) _
        Handles MyBase.FormClosing

'When the converter closes, frmRD will reappear
    frmRD.Show()
    End Sub
End Class

Points of Interest

This project has brought only good things to my household. Now my parents have got something to look forward to when they log on to their computers.

History

  • 15 December, 2007: Article posted

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here