Thursday, September 8, 2011

Auto Desktop Background VBS Script

I was searching for this for quite a bit to get this super easy task right, so here it is. Based on some code I found on some place on the web.

Simply download a set of nice desktop backgrounds on the web, put them all in one folder and then create a vbs file with the following content in this folder. Make sure to change strFolder=... in the top to your desired folder.

Filename: randomdesktop.vbs
Option Explicit
Dim WshShell, oFolder, intNumber, strValue, i, oFile, strFolder, intFolders, intFiles, serialIndex, sleepTime, serialFolder
strFolder = "d:\tools\bg\"
Set WshShell = WScript.CreateObject("Wscript.Shell")
Set oFolder = WScript.CreateObject("Scripting.FileSystemObject").GetFolder(strFolder)
serialIndex = 0
            intFiles = oFolder.Files.Count
            intFolders = oFolder.Subfolders.Count
            Randomize
            intNumber = Int((intFiles + intFolders) * Rnd) + 1
            If intNumber > intFiles Then
                sleepTime = 10
                serialIndex = 1
                i = intFiles
                For Each serialFolder In oFolder.Subfolders  
                    i = i + 1
                    If i = intNumber Then Exit For                                                        
                Next
                i = 0
                For Each oFile In serialFolder.Files  
                    i = i + 1
                    If i = serialIndex Then Exit For                                                      
                Next
            Else
                sleepTime = 10
                i = 0
                For Each oFile In oFolder.Files  
                    i = i + 1
                    If i = intNumber Then Exit For                                                      
                Next
            End If
        If oFile.Path <> strValue Then
            strValue = oFile.Path
        End If
    Set oFile = Nothing
    WshShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper", strValue
    WshShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters", 1, False
Set WshShell = Nothing
Set oFolder = Nothing


When executed, the script will select a random file from the folder specified and set it to the desktop background. I have placed it it my startup folder and now I have a new desktop image every day. :-)