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()”
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?
What error do you get?
Do you CoUninitialize as well?
Check out this link:
https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-couninitialize