使用C++和Windows API编程实现更改壁纸

10

我一直在尝试使用Qt和mingw32编写一个应用程序,下载图像并将它们设置为背景墙纸。我已经阅读了几篇关于如何在VB和C#中实现此目的的文章,以及在某种程度上如何在C++中实现。我当前调用SystemParametersInfo,似乎所有参数都正确(没有编译器错误),但是失败了。没有大崩溃声,只是返回一个0GetLastError()同样返回一个无意义的0

下面是我正在使用的代码(稍作修改,以便您不必查看对象内部)。

#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;
    }
}

你尝试使用位图文件而不是PNG / JPG格式了吗? - NG.
4个回答

10

可能是因为 SystemParametersInfo 需要一个 LPWSTR(指向 wchar_t 的指针)。

尝试这样做:

LPWSTR test = L"C:\\Documents and Settings\\Owner\\My Documents\\Wallpapers\\wallpaper.png";

result = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, test, SPIF_UPDATEINIFILE);

如果这个代码可以正常运行(请确保使用几个不同的文件进行测试),那么你需要将你的char *转换为LPWSTR。我不确定Qt是否提供这些服务,但一个可能会有帮助的函数是MultiByteToWideChar


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

这句话应该改为:“这不应该是:”。
"C:\\Documents and Settings\\Owner\\My Documents\\Wallpapers\\wallpaper.png";

哦,没错。但那不是错误所在。在实际程序中,QString 是由另一个函数正确填充的 :) 但是感谢你发现了我的错误 :) - Blue Peppers

0
你可以使用SetTimer来触发一个变化。
#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;
}

-1
std::string file_path = "C:\\Image.png";
LPVOID FilePath = (LPVOID)file_path.c_str();
SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, FilePathBuffer, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);

根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,以帮助他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接