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”;
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()”

Leave a Reply

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