根据本地图片路径,把图片设置为桌面壁纸。
需要先添加“WallpaperHelper”类 。 项目 => 添加 => 类。
“WallpaperHelper”类代码如下:
class WallpaperHelper
{
[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
/// <summary>
/// 更换壁纸
/// </summary>
/// <param name="fileName">壁纸文件的路径</param>
/// <returns>操作结果:true为更换成功,false为更换失败</returns>
public static bool ChangeWallPaper(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return false;
}
if (File.Exists(fileName) == false)
{
return false;
}
fileName = Path.GetFullPath(fileName);
var nResult = SystemParametersInfo(20, 1, fileName, 0x1 | 0x2); //更换壁纸
if (nResult == 0)
{
return false;
}
else
{
RegistryKey hk = Registry.CurrentUser;
RegistryKey run = hk.CreateSubKey(@"Control Panel\Desktop\");
run.SetValue("Wallpaper", fileName);
return true;
}
}
}
添加类后,提供路径参数引用即可:
string fileName = @"D:\素材\横屏图片集\森林.jpg";
WallpaperHelper.ChangeWallPaper(fileName);