Change wallpaper programmatically with C ++ and windows api

I am trying to write an application using Qt and mingw32 to download images and set them as background. I read several articles on the Internet about how to do this, in VB and C #, and to some extent how to do it in C ++. I am currently calling SystemParametersInfo so that it seems to be all valid arguments (no compiler errors) and it fails. No big catastrophe disasters, only 0 returned. GetLastError() returns an equally enlightening 0 .

Below is the code I'm using (in a slightly modified form, so you don't need to look at internal objects).

 #include <windows.h> #include <iostream> #include <QString> void setWall() { QString filepath = "C:\\Documents and Settings\\Owner\\My Documents\\Wallpapers\\wallpaper.png"; char path[150]; strcpy(path, currentFilePath.toStdString().c_str()); char *pathp; pathp = path; cout << path; int result; result = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, pathp, SPIF_UPDATEINIFILE); if (result) { cout << "Wallpaper set"; } else { cout << "Wallpaper not set"; cout << "SPI returned" << result; } } 
+6
c ++ qt winapi wallpaper
source share
3 answers

Maybe SystemParametersInfo expects an LPWSTR (pointer to wchar_t ).

Try the following:

 LPWSTR test = L"C:\\Documents and Settings\\Owner\\My Documents\\Wallpapers\\wallpaper.png"; result = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, test, SPIF_UPDATEINIFILE); 

If this works (try doing this with several different files to make sure), you need to convert char * to LPWSTR . I'm not sure Qt offers these services, but one of the features that might help is MultiByteToWideChar .

+10
source share
 "C:\Documents and Settings\Owner\My Documents\Wallpapers\wallpaper.png"; 

must not be:

 "C:\\Documents and Settings\\Owner\\My Documents\\Wallpapers\\wallpaper.png"; 
+2
source share

You can use SetTimer to trigger the change.

 #define STRICT 1 #include <windows.h> #include <iostream.h> VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { LPWSTR wallpaper_file = L"C:\\Wallpapers\\wallpaper.png"; int return_value = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, wallpaper_file, SPIF_UPDATEINIFILE); cout << "Programmatically change the desktop wallpaper periodically: " << dwTime << '\n'; cout.flush(); } int main(int argc, char *argv[], char *envp[]) { int Counter=0; MSG Msg; UINT TimerId = SetTimer(NULL, 0, 2000, &TimerProc); //2000 milliseconds cout << "TimerId: " << TimerId << '\n'; if (!TimerId) return 16; while (GetMessage(&Msg, NULL, 0, 0)) { ++Counter; if (Msg.message == WM_TIMER) cout << "Counter: " << Counter << "; timer message\n"; else cout << "Counter: " << Counter << "; message: " << Msg.message << '\n'; DispatchMessage(&Msg); } KillTimer(NULL, TimerId); return 0; } 
0
source share

All Articles