Windows7获取、更换桌面背景,C#
使用的API原型是 BOOL SystemParametersinfo(UINT uiAction,UINT uiParam,PVOID pvParam,UINT fWinlni);
在C#中定义如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 查询或设置系统级参数 3 /// </summary> 4 /// <param name="uAction"></param> 5 /// <param name="uParam"></param> 6 /// <param name="lpvParam"></param> 7 /// <param name="fuWinIni"></param> 8 /// <example></example> 9 /// <returns></returns> 10 [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] 11 public static extern int SystemParametersInfo(UAction uAction, int uParam, StringBuilder lpvParam, int fuWinIni);
其中UAction类型的参数定义为:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public enum UAction 2 { 3 /// <summary> 4 /// 设置桌面背景图片 5 /// </summary> 6 SPI_SETDESKWALLPAPER = 0x0014, 7 /// <summary> 8 /// 获取桌面背景图片 9 /// </summary> 10 SPI_GETDESKWALLPAPER = 0x0073, 11 }
首先是获取桌面背景,调用方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public string GetBackgroud() 2 { 3 StringBuilder s = new StringBuilder(300); 4 APIHelper.SystemParametersInfo(UAction.SPI_GETDESKWALLPAPER, 300, s, 0); 5 return s.ToString(); 6 }
再是设置桌面背景:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 设置桌面背景 3 /// </summary> 4 /// <param name="fileName">图片绝对路径</param> 5 /// <returns></returns> 6 public int SetBackgroud(string fileName) 7 { 8 int result = 0; 9 if (File.Exists(fileName)) 10 { 11 StringBuilder s = new StringBuilder(fileName); 12 result = APIHelper.SystemParametersInfo(UAction.SPI_SETDESKWALLPAPER, 0, s, 0x2); 13 } 14 return result; 15 }
返回0表示设置失败,1表示成功。
以上内容网上都能搜到,
但是在使用过程中,发现通过上述的设置方法,虽然能改变桌面背景,但是右键桌面→个性化→桌面背景里的图片并没有改变。
查找资料后,才知道是注册表没有设置。
注册表:HKEY_CURRENT_USER\Control Panel\Desktop
修改里面Wallpaper的值为图片路径即可
相关设置注册表代码如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 设置注册表选项 3 /// </summary> 4 /// <param name="optionsName">注册表项名称</param> 5 /// <param name="optionsData">注册表项值</param> 6 /// <param name="msg"></param> 7 /// <returns></returns> 8 public static bool SetOptions(string optionsName, string optionsData, ref string msg) 9 { 10 bool returnBool = true; 11 RegistryKey classesRoot = Registry.CurrentUser; 12 RegistryKey registryKey = classesRoot.OpenSubKey(@"Control Panel\Desktop", true); 13 try 14 { 15 if (registryKey != null) 16 { 17 registryKey.SetValue(optionsName.ToUpper(), optionsData); 18 } 19 else 20 { 21 returnBool = false; 22 } 23 } 24 catch 25 { 26 returnBool = false; 27 msg = "读取注册表出现异常、"; 28 } 29 finally 30 { 31 classesRoot.Close(); 32 registryKey.Close(); 33 } 34 return returnBool; 35 }
注:XP下更换背景只支持BMP格式,需要将jpg文件读取,转换成BMP格式,再设置。