How to change the desktop wallpaper, programmatically.
![]()
I bet at least once in your lifetime, you’ve used desktop wallpaper changing applications like webshots - which sets beautiful wallpaper to the desktop automatically after certain time intervals. When i started leaning windows programming, i wonder – how this application changes the wallpaper. The answer is – IActiveDesktop.
![]()
The IActiveDesktop is a com interface exposed by windows shell. You’ve to call the SetWallpaper() function and then apply the changes by calling ApplyChanges(). See the code snippet below.
#include "shlobj.h"
...
HRESULT hr;
IActiveDesktop* pActiveDesktop = 0;
// Initialize COM.
::CoInitialize( 0 );
// Get the ActiveDesktop Interface.
hr = CoCreateInstance( CLSID_ActiveDesktop,
0,
CLSCTX_INPROC_SERVER,
IID_IActiveDesktop,
(void**) &pActiveDesktop );
// Check whether CoCreateInstance is success.
if( FAILED( hr ))
{
// Creating ActiveDesktop interface pointer failed.
AfxMessageBox( _T("Error Occurred!"));
}
// SetWallpaper() accepts the wallpaper path only as WideChar.
LPCWSTR strWallPaper = L"C:\\Autumn Leaves.jpg";
// Set the new wallpaper.
pActiveDesktop->SetWallpaper( strWallPaper, 0 );
// Apply changes to refresh desktop.
pActiveDesktop->ApplyChanges( AD_APPLY_ALL );
// Release the interface pointer.
pActiveDesktop->Release();
// Uninitialize COM.
::CoUninitialize();
![]()
While compiling this, certainly you will hit the following error.
error C2065: 'IActiveDesktop' : undeclared identifier error C2065: 'pActiveDesktop' : undeclared identifier error C2106: '=' : left operand must be l-value
Don’t worry. Its a known issue. For solving this error, take StdAfx.h and include wininet.h header just before afxdisp.h. I assume you’re using MFC. See the sample below.
#include <afxwin.h>
#include <afxext.h>
#include "wininet.h"
#include <afxdisp.h>
#include <afxdtctl.h>
Keen to know more? See KB196342 for more details.
![]()
Trargeted Audience – Intermediate.
Thanks. Work perfectly on Visual Studio 2010. Tested on XP Mode, Vista and Windows 7 x64, no problems.
Thanks. Work perfectly on Visual Studio 2010. Tested on WinXP Mode, Vindows 7 x64, no problems.
Ah! So It works fine. My pleasure.
Thanks for sharing your experience, Nemesis.
Best Regards,
Jijo.
Thank you for sharing this info! I tried with win32 console application and i got the same errors you’d mentioned. It was solved when i put wininet.h between windows.h and shlobj.h
Thanks,
Varun
For folks using C#, there’s an solution here:
http://www.codeproject.com/KB/dotnet/SettingWallpaperDotNet.aspx
The solution on CodeProject doesn’t use IActiveDesktop via COM either. It just sets some registry keys in HKCU/Control Panel/Desktop, and then calls SystemParametersInfo() which is in user32.dll.