C#更换桌面壁纸

WallpaperHelper.cs文件:
复制代码
using Microsoft.Win32;
using System.IO;
using System.Runtime.InteropServices;

namespace NPOIDemo
{
    /// <summary>
    /// 更换壁纸
    /// </summary>
    public 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;
            }
        }
    }
}
复制代码

调用示例:

var fileDialog = new OpenFileDialog();
fileDialog.Filter = "所有文件(*.*)|*.*";
if (fileDialog.ShowDialog() == true)
{
    var fileName = fileDialog.FileName;
    WallpaperHelper.ChangeWallPaper(fileName);
}

 

posted @   wzwyc  阅读(1145)  评论(2编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示