2

I try to change my desktop wallpaper. It works just fine when I use it like this:

SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, "C:\\1.jpg", SPIF_SENDCHANGE);

But when I use it like this, the desktop wallpaper is set completly black:

std::string s = "C:\\1.jpg";
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, &s, SPIF_SENDCHANGE);

I tried to get some more info via using GetLastError(), but the return value is just 0. I also tried to use .png-files, but this doesn't change anything.

Any ideas what I am doing wrong?

aasoo
  • 31
  • 1
  • 4

2 Answers2

8

Try this:

SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (void*)s.c_str(), SPIF_SENDCHANGE);

The SystemParametersInfo function doesn't accept std::string pointer as path, it accepts a null-terminated char array. Which is what the c_str() method of std::string provides.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • windows api are only compatible with C language type system and interface? – Angelus Mortis Jan 10 '16 at 21:01
  • almost the solution. I tried to use c_str(), but it says it can't convert from "const char *" to "PVOID" But it works fine if you use it like this: `(void*)s.c_str()`. Thx :) – aasoo Jan 10 '16 at 21:10
  • 2
    @AngelusMortis wrong conclusion; rather the Windows API is only compatible with C strings, not C++ `` objects – andlabs Jan 10 '16 at 21:45
  • 1
    @andlabs: Angelus's conclusion was not wrong. The Win32 API is designed for C. Any C-compatible language can use it. it makes very few accommodations for C++. – Remy Lebeau Jan 10 '16 at 22:13
  • @RemyLebeau right; perhaps I misinterpreted the statement then – andlabs Jan 10 '16 at 23:01
  • You do not need the cast to `void*` here. Calling the `c_str()` member function is enough. Eschew casts whenever possible. – Cody Gray - on strike Jan 11 '16 at 13:17
  • 2
    @CodyGray: no, you do need the cast, it's needed to drop the `const` modifier. You can, however, cast to `char*` rather than `void*`. – Violet Giraffe Jan 11 '16 at 13:41
-1

Instead of using "C:\\1.jpg", use @"C:\1.jpg". This resolves the issue.