Tuesday, November 16, 2010

How to modify Desktop Wallpaper using VBScript

From my experience, the best way to change Desktop wallpaper is via vbs file.

below is the code for the vbs file that assumes path to the wallpaper will be paaed as an argument to the file below:

Set oShell = CreateObject("WScript.Shell")
Set oSHApp = CreateObject("Shell.Application")

if WScript.Arguments.Count > 0 then

'Set Wallpaper path
sWallPaper = WScript.Arguments(0)

' Update Wallpaper in registry
oShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper", sWallPaper

'Refresh Screen by running Control Panel application.
'If the application is already open, it will activate the running instance.
oSHApp.ControlPanelItem cstr("desk.cpl")

' Loop and wait until Display Properties is loaded.
Do Until oShell.AppActivate ("Display Properties")
oShell.SendKeys "{DOWN}{UP}{TAB 3}~"
end if

The code above works like a charm, I find it to be a lot more efficient than running a batch file with the following code, which often does not refresh the Desktop after modifying the registry:

reg add "HKCU\Control Panel\Desktop" /v Wallpaper /t REG_SZ /d %1 /f
RUNDLL32.exe user32.dll,UpdatePerUserSystemParameters

1 comment: