WallpaperTool.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace Azylee.Core.WindowsUtils.APIUtils.WallpaperUtils
  7. {
  8. /// <summary>
  9. /// 系统桌面壁纸工具类
  10. /// </summary>
  11. public static class WallpaperTool
  12. {
  13. #region 获取windows桌面背景
  14. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  15. public static extern int SystemParametersInfo(int uAction, int uParam, StringBuilder lpvParam, int fuWinIni);
  16. private const int SPI_GETDESKWALLPAPER = 0x0073;
  17. #endregion
  18. #region 设置windows桌面背景
  19. [DllImport("user32.dll")]
  20. private static extern bool SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
  21. #endregion
  22. /// <summary>
  23. /// 获取当前桌面壁纸路径
  24. /// </summary>
  25. /// <returns></returns>
  26. public static string Get()
  27. {
  28. try
  29. {
  30. //定义存储缓冲区大小
  31. StringBuilder s = new StringBuilder(300);
  32. //获取Window 桌面背景图片地址,使用缓冲区
  33. SystemParametersInfo(SPI_GETDESKWALLPAPER, 300, s, 0);
  34. //缓冲区中字符进行转换
  35. return s.ToString(); //系统桌面背景图片路径
  36. }
  37. catch { return null; }
  38. }
  39. /// <summary>
  40. /// 设置当前桌面背景
  41. /// </summary>
  42. /// <param name="path"></param>
  43. /// <returns></returns>
  44. public static bool Set(string path)
  45. {
  46. try
  47. {
  48. SystemParametersInfo(20, 0, path, 0x01 | 0x02);
  49. return true;
  50. }
  51. catch { return false; }
  52. }
  53. }
  54. }