概述
在域环境下的计算机正常情况下修改了Windows系统的壁纸是需要重启才能生效的,因为在某些情况下,系统可能会缓存壁纸设置,导致更改无法立即生效。
壁纸的缓存目录位于
C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Themes\CachedFiles
解决办法
更改当前桌面壁纸让执行立即生效,Powershell 可以调用Windows API 实现,下面这个函数能立即更改当前壁纸。
function Set-Wallpaper
{
param(
[Parameter(Mandatory=$true)]
$Path,
[ValidateSet('Center', 'Stretch')]
$Style = 'Stretch'
)
Add-Type @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
public enum Style : int
{
Center, Stretch
}
public class Setter {
public const int SetDesktopWallpaper = 20;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper ( string path, Wallpaper.Style style ) {
SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
switch( style )
{
case Style.Stretch :
key.SetValue(@"WallpaperStyle", "2") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Center :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
}
key.Close();
}
}
}
"@
[Wallpaper.Setter]::SetWallpaper( $Path, $Style )
}
Set-Wallpaper -Path 'C:\background2.jpg'
执行后,壁纸的缓存同时也立即刷新,效果如下所示。