How to change Desktop background image in C++

In this post I am sharing a piece of code that I use to change Desktop Background image in Qt (C++) for Windows. This can be used in newer Windows versions (Windows 8 and later) and I have already tested it with Windows 10 64 bit. It involves using Windows interfaces in Qt.

First add following to your .PRO file:

LIBS += -lOle32


You also need to add the following to your header file:

#include "shobjidl.h"

Finally, using the source code below you can change Desktop wallpaper. For example you can write a program that changes your PC wallpaper every hour or so.

HRESULT hr = CoInitialize(nullptr);
IDesktopWallpaper* pDesktopWallpaper = nullptr;
hr = CoCreateInstance(__uuidof(DesktopWallpaper), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&pDesktopWallpaper));
if (FAILED(hr))
{
	qDebug() << "error";
}
else
{
	pDesktopWallpaper->SetWallpaper(nullptr, QString("C:\\Users\\Amin\Desktop\\test.jpg").toStdWString().c_str());
}

Obviously you need to use your own file path instead of the file that I used in the example source above: “C:\Users\Amin\Desktop\test.jpg”

If you are not using Qt, you need to remove “.toStdWString().c_str()”



2 Replies to “How to change Desktop background image in C++”

  1. How do you exit your program? I have put:
    HRESULT hr = CoInitialize(nullptr);
    hr = CoCreateInstance(__uuidof(DesktopWallpaper), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&m_wpDesktop));
    //HRESULT hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER,

    in the Dialog initialization
    CDewacha4::CDewacha4()

    and then in
    CDewacha4Dlg::~CDewacha4Dlg()
    {
    if (m_wpDesktop != nullptr)
    {
    m_wpDesktop->Release();
    m_wpDesktop = nullptr;
    }
    }
    However, I am getting an error message when the program exits that I’m guessing means that something has not been properly released.

    Any suggestions?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.