Set Desktop Wallpaper using non-bitmap in Win32 C++

来源:互联网 发布:2017淘宝开店照片 编辑:程序博客网 时间:2024/06/18 11:28

One day,I want to set the desktop wallpaper by the application which
I wrote using Win32 in c++.First,I used the api
SystemParametersInfo(SPI_SETDESKWALLPAPER,TRUE,(LPVOID)"E://my_docs//test.jpg",SPIF_SENDWININICHANGE| SPIF_UPDATEINIFILE);
But it can not work.So I checked with MSDN:

SPI_SETDESKWALLPAPER
Sets the desktop wallpaper. The value of the pvParam parameter determines the new wallpaper. To specify a wallpaper bitmap, set pvParam to point to a null-terminated string containing the full path to the bitmap file. Setting pvParam to "" removes the wallpaper. Setting pvParam to SETWALLPAPER_DEFAULT or NULL reverts to the default wallpaper.
Starting with Windows Vista, pvParam can specify a .jpg file.

So I tried the Google,it told me as below and that can be worked normally.

  139 BOOL SetWPByActiveDesktop(LPCTSTR lpszPath)

  140 {

  141     if ( lpszPath == NULL )

  142         return FALSE ;

  143 #if 1

  144     CoInitialize(NULL);

  145 

  146     HRESULT hr;

  147     IActiveDesktop* pIAD;

  148     hr = CoCreateInstance( CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER,IID_IActiveDesktop, (void**)&pIAD);

  149 

  150     if ( !SUCCEEDED(hr) )

  151         return FALSE;

  152 

  153     //set activedesktop options,turn on the AD.

  154     COMPONENTSOPT co = {0};

  155     co.dwSize = sizeof(COMPONENTSOPT);

  156     co.fEnableComponents = TRUE;

  157     co.fActiveDesktop = TRUE;

  158     hr = pIAD->SetDesktopItemOptions(&co, 0);

  159     if ( !SUCCEEDED(hr) )

  160         return FALSE;

  161 

  162     //pay attention the parameter passed to IActiveDesktop.if app is unicode,ignore

  163     WCHAR wszPath[MAX_PATH]={0};

  164     //LPTSTR lpStr = strPath.GetBuffer(strPath.GetLength());

  165     MultiByteToWideChar(CP_ACP, 0, lpszPath, -1, wszPath, MAX_PATH);

  166     //strPath.ReleaseBuffer();

  167 

  168     //set the wallpaper

  169     hr = pIAD->SetWallpaper(wszPath, 0);

  170     if ( !SUCCEEDED(hr) )

  171         return FALSE;

  172 

  173     // Set wallpaper style such as title,center,stretch

  174     WALLPAPEROPT wp = {0};

  175     wp.dwSize = sizeof(WALLPAPEROPT);

  176     wp.dwStyle |= WPSTYLE_CENTER;

  177     hr = pIAD->SetWallpaperOptions(&wp, 0);

  178     if ( !SUCCEEDED(hr) )

  179         return FALSE;

  180 

  181     // 应用改变

  182     hr = pIAD->ApplyChanges(AD_APPLY_ALL);

  183     if ( !SUCCEEDED(hr) )

  184         return FALSE;

  185 

  186     // RELEASE

  187     pIAD->Release();

  188 

  189     CoUninitialize();

  190 #endif

  191 

  192     return TRUE; 

  193 }

Testing passed in VC++6 SP6-win32 application.