How to change the desktop wallpaper, programmatically.

27 04 2008


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.

Advertisements