更改桌面背景

C++代码(一次运行就有效,但是32位需要自行编译)

#include <windows.h>
#include <winreg.h>

int main() {
    // 壁纸路径
    const char* wallpaperPath = "D:\\test.jpg";

    // 打开注册表键
    HKEY hKey;
    RegOpenKeyEx(HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, KEY_ALL_ACCESS, &hKey);

    // 设置壁纸样式为适应(WallpaperStyle = 6,TileWallpaper = 0)
    const char* wallpaperStyle = "6";
    const char* tileWallpaper = "0";
    RegSetValueEx(hKey, "WallpaperStyle", 0, REG_SZ, (BYTE*)wallpaperStyle, strlen(wallpaperStyle) + 1);
    RegSetValueEx(hKey, "TileWallpaper", 0, REG_SZ, (BYTE*)tileWallpaper, strlen(tileWallpaper) + 1);

    // 关闭注册表键
    RegCloseKey(hKey);

    // 更改壁纸
    SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (void*)wallpaperPath, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);

    return 0;
}

 

vbs代码(需要运行很多次才有效)

' 创建一个Shell对象以更改壁纸
Set objShell = CreateObject("WScript.Shell")

' 设置壁纸路径
wallpaperPath = "D:\\test.jpg"

' 打开壁纸设置的注册表键
Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
strKeyPath = "Control Panel\Desktop"
objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, "Wallpaper", wallpaperPath
objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, "WallpaperStyle", "6"
objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, "TileWallpaper", "0"

' 发送WM_SETTINGCHANGE消息以更新桌面
objShell.Run "RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True

WScript.Quit

 

 
posted @ 2023-10-30 08:20  byxiaobai  阅读(66)  评论(0编辑  收藏  举报