3

I am looking to change the Windows desktop background wallpaper in C++ using the Windows API.

I have read the following posts on this topic:

Problem:

When I execute the code, the desktop background changes to completely black like in the post above (yes, I did try the suggested fix in that post. No luck.)

Code:

#include <windows.h>

int main() {
    std::string s = "C:\\picture.jpg";
    SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID*)s.c_str(), SPIF_SENDCHANGE);
    return 0;
}

I have also tried just (void*) instead of (PVOID*) above and an L in front of the string. Nothing works so far.

SOLVED:

Changing SystemParametersInfo to SystemParametersInfoA (as suggested in the comment and answer) did the trick.

learnerX
  • 1,022
  • 1
  • 18
  • 44
  • 2
    Check the return and use [`GetLastError()`](https://learn.microsoft.com/en-us/windows/desktop/api/errhandlingapi/nf-errhandlingapi-getlasterror). Also, are you compiling for Unicode? – 001 Jun 11 '19 at 17:46
  • 3
    Use SystemParametersInfoA() to ensure it is compatible with std::string – Hans Passant Jun 11 '19 at 18:04
  • 1
    I agree that it's most likely a wide vs narrow char issue - `SystemParametersInfo()` info is a macro for either SystemParametersInfoA or SystemParametersInfoW depending on the unicode #define. You could make it windows style explicitly by doing `const wchar_t * s = L"C:\Picture.jpg";` and calling it with SystemParametersInfoW (or visa-versa with `const char` and SystemParametersA) – Hal Jarrett Jun 11 '19 at 18:12

1 Answers1

4

I believe you should use a wchar_t as input for SystemParametersInfo() instead of a string and also use SystemParametersInfoW().

The following code worked for me:

#include <windows.h>
#include <iostream>


int main() {
    const wchar_t *path = L"C:\\image.png";
    int result;
    result = SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void *)path, SPIF_UPDATEINIFILE);
    std::cout << result;        
    return 0;
}

Where SystemParametersInfoW() should return true if it manages to change the background. I print it out as result for clarity when running the application.

darclander
  • 1,526
  • 1
  • 13
  • 35