码迷,mamicode.com
首页 > Windows程序 > 详细

C#更换桌面壁纸

时间:2021-02-26 13:00:29      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:pen   namespace   entry   space   empty   get   style   setvalue   rop   

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

 

C#更换桌面壁纸

标签:pen   namespace   entry   space   empty   get   style   setvalue   rop   

原文地址:https://www.cnblogs.com/wzwyc/p/14446840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!