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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM