首页 > 系统相关 >windows系统桌面壁纸切换的三种csharp办法,兼容win10及旧版,还有一个现成桌面小程序

windows系统桌面壁纸切换的三种csharp办法,兼容win10及旧版,还有一个现成桌面小程序

时间:2024-05-27 21:33:09浏览次数:28  
标签:桌面壁纸 windows void csharp int MarshalAs public string UnmanagedType

我自己用这些代码做的小app如下:

 

最新版本已经改成了服务的方式,也可以选择性添加系统的右键菜单,并且我自己使用的源码库已经开源到了nuget,大家可以直接拿来做二次开发,

新版的下载地址为:https://www.zhaimaojun.cn/P/桌面壁纸管理器/

开源库为(可以直接在vs的nuget包管理中搜索到):https://www.nuget.org/packages/WindowsAPI/

 

第一种,user32.dll

 

1 2 3 4 5 6 7 8 9 10 /// <summary>         /// 调用外部切换壁纸的方法         /// </summary>         /// <param name="uAction"></param>         /// <param name="uParam"></param>         /// <param name="lpvParam"></param>         /// <param name="fuWinIni"></param>         /// <returns></returns>         [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]         public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

就是一种很常用,好像兼容性最好的办法吧,但是,使用的局限性很大,多显示器情况下会导致所有显示器使用相同的壁纸!而且无法区分多个显示器

第二种,IActiveDesktop

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 public class ActiveDesktopCom     {         /// <summary>         /// 壁纸的显示方式         /// </summary>         public enum WPSTYLE         {             /// <summary>             /// 居中             /// </summary>             CENTER = 0,             /// <summary>             /// 平铺             /// </summary>             TILE = 1,             /// <summary>             /// 拉伸             /// </summary>             STRETCH = 2,             /// <summary>             /// 适应             /// </summary>             adapt = 3,             /// <summary>             /// 填充             /// </summary>             FILL = 4,             /// <summary>             /// 跨区             /// </summary>             Transregional = 5,         }           struct WALLPAPEROPT         {             public int dwSize;             public WPSTYLE dwStyle;         }           struct COMPONENTSOPT         {             public int dwSize;             [MarshalAs(UnmanagedType.Bool)]             public bool fEnableComponents;             [MarshalAs(UnmanagedType.Bool)]             public bool fActiveDesktop;         }           struct COMPPOS         {             public const int COMPONENT_TOP = 0x3FFFFFFF;             public const int COMPONENT_DEFAULT_LEFT = 0xFFFF;             public const int COMPONENT_DEFAULT_TOP = 0xFFFF;               public int dwSize;             public int iLeft;             public int iTop;             public int dwWidth;             public int dwHeight;             public int izIndex;             [MarshalAs(UnmanagedType.Bool)]             public bool fCanResize;             [MarshalAs(UnmanagedType.Bool)]             public bool fCanResizeX;             [MarshalAs(UnmanagedType.Bool)]             public bool fCanResizeY;             public int iPreferredLeftPercent;             public int iPreferredTopPercent;         }           [Flags]         enum ITEMSTATE         {             NORMAL = 0x00000001,             FULLSCREEN = 00000002,             SPLIT = 0x00000004,             VALIDSIZESTATEBITS = NORMAL | SPLIT | FULLSCREEN,             VALIDSTATEBITS = NORMAL | SPLIT | FULLSCREEN | unchecked((int)0x80000000) | 0x40000000         }           struct COMPSTATEINFO         {             public int dwSize;             public int iLeft;             public int iTop;             public int dwWidth;             public int dwHeight;             public int dwItemState;         }           enum COMP_TYPE         {             HTMLDOC = 0,             PICTURE = 1,             WEBSITE = 2,             CONTROL = 3,             CFHTML = 4,             MAX = 4         }           [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]         struct COMPONENT         {             private const int INTERNET_MAX_URL_LENGTH = 2084;   //   =                                                                   // INTERNET_MAX_SCHEME_LENGTH   (32)   +   "://\0".Length   +                                                                   // INTERNET_MAX_PATH_LENGTH   (2048)                public int dwSize;             public int dwID;             public COMP_TYPE iComponentType;             [MarshalAs(UnmanagedType.Bool)]             public bool fChecked;             [MarshalAs(UnmanagedType.Bool)]             public bool fDirty;             [MarshalAs(UnmanagedType.Bool)]             public bool fNoScroll;             public COMPPOS cpPos;             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]             public string wszFriendlyName;             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = INTERNET_MAX_URL_LENGTH)]             public string wszSource;             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = INTERNET_MAX_URL_LENGTH)]             public string wszSubscribedURL;   #if AD_IE5     public   int   dwCurItemState;       public   COMPSTATEINFO   csiOriginal;       public   COMPSTATEINFO   csiRestored;   #endif         }           enum DTI_ADTIWUI         {             DTI_ADDUI_DEFAULT = 0x00000000,             DTI_ADDUI_DISPSUBWIZARD = 0x00000001,             DTI_ADDUI_POSITIONITEM = 0x00000002,         }           [Flags]         enum AD_APPLY         {             SAVE = 0x00000001,             HTMLGEN = 0x00000002,             REFRESH = 0x00000004,             ALL = SAVE | HTMLGEN | REFRESH,             FORCE = 0x00000008,             BUFFERED_REFRESH = 0x00000010,             DYNAMICREFRESH = 0x00000020         }           [Flags]         enum COMP_ELEM         {             TYPE = 0x00000001,             CHECKED = 0x00000002,             DIRTY = 0x00000004,             NOSCROLL = 0x00000008,             POS_LEFT = 0x00000010,             POS_TOP = 0x00000020,             SIZE_WIDTH = 0x00000040,             SIZE_HEIGHT = 0x00000080,             POS_ZINDEX = 0x00000100,             SOURCE = 0x00000200,             FRIENDLYNAME = 0x00000400,             SUBSCRIBEDURL = 0x00000800,             ORIGINAL_CSI = 0x00001000,             RESTORED_CSI = 0x00002000,             CURITEMSTATE = 0x00004000,             ALL = TYPE | CHECKED | DIRTY | NOSCROLL | POS_LEFT | SIZE_WIDTH |                 SIZE_HEIGHT | POS_ZINDEX | SOURCE |                 FRIENDLYNAME | POS_TOP | SUBSCRIBEDURL | ORIGINAL_CSI |                 RESTORED_CSI | CURITEMSTATE         }           [Flags]         enum ADDURL         {             SILENT = 0x0001         }           [             ComImport(),             Guid("F490EB00-1240-11D1-9888-006097DEACF9"),             InterfaceType(ComInterfaceType.InterfaceIsIUnknown)         ]         interface IActiveDesktop         {             void ApplyChanges(AD_APPLY dwFlags);             void GetWallpaper([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pwszWallpaper, int cchWallpaper, int dwReserved);             void SetWallpaper([MarshalAs(UnmanagedType.LPWStr)] string pwszWallpaper, int dwReserved);             void GetWallpaperOptions(ref WALLPAPEROPT pwpo, int dwReserved);             void SetWallpaperOptions([In] ref WALLPAPEROPT pwpo, int dwReserved);             void GetPattern([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pwszPattern, int cchPattern, int dwReserved);             void SetPattern([MarshalAs(UnmanagedType.LPWStr)] string pwszPattern, int dwReserved);             void GetDesktopItemOptions(ref COMPONENTSOPT pco, int dwReserved);             void SetDesktopItemOptions([In] ref COMPONENTSOPT pco, int dwReserved);             void AddDesktopItem([In] ref COMPONENT pcomp, int dwReserved);             void AddDesktopItemWithUI(IntPtr hwnd, [In] ref COMPONENT pcomp, DTI_ADTIWUI dwFlags);             void ModifyDesktopItem([In] ref COMPONENT pcomp, COMP_ELEM dwFlags);             void RemoveDesktopItem([In] ref COMPONENT pcomp, int dwReserved);             void GetDesktopItemCount(out int lpiCount, int dwReserved);             void GetDesktopItem(int nComponent, ref COMPONENT pcomp, int dwReserved);             void GetDesktopItemByID(IntPtr dwID, ref COMPONENT pcomp, int dwReserved);             void GenerateDesktopItemHtml([MarshalAs(UnmanagedType.LPWStr)] string pwszFileName, [In] ref COMPONENT pcomp, int dwReserved);             void AddUrl(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszSource, [In] ref COMPONENT pcomp, ADDURL dwFlags);             void GetDesktopItemBySource([MarshalAs(UnmanagedType.LPWStr)] string pwszSource, ref COMPONENT pcomp, int dwReserved);         }           [             ComImport(),             Guid("75048700-EF1F-11D0-9888-006097DEACF9")         ]         class ActiveDesktop   /*   :   IActiveDesktop   */   { }         public class OLE32DLL         {             [DllImport("ole32.dll", SetLastError = true)]             public static extern int CoUninitialize();               [DllImport("ole32.dll", SetLastError = true)]             public static extern int CoInitialize(int pvReserved);               [DllImport("ole32.dll", CharSet = CharSet.Unicode)]             public static extern int CLSIDFromString(string lpsz, out Guid pclsid);               [DllImport("ole32.dll", ExactSpelling = true, PreserveSig = false)]             [return: MarshalAs(UnmanagedType.Interface)]             public static extern object CoCreateInstance(                 [In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid,                 int pUnkOuter,                 int dwClsContext,                 [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid             );         }         /// <summary>         /// 兼容win7版本以前版本系统的修改壁纸         /// </summary>         /// <param name="filename"></param>         /// <returns></returns>         public static bool SetActiveDesktop(string filename, WPSTYLE dwstyle = WPSTYLE.FILL)         {             try             {                 const int NULL = 0;                 const int S_OK = 0;                 const int CLSCTX_ALL = 23;                   Guid IID_IActiveDesktop = new Guid("F490EB00-1240-11D1-9888-006097DEACF9");                 Guid CLSID_ActiveDesktop = new Guid("75048700-EF1F-11D0-9888-006097DEACF9");                   if (System.Threading.Thread.CurrentThread.GetApartmentState() != System.Threading.ApartmentState.STA && OLE32DLL.CoInitialize(NULL) < S_OK)                     throw new Exception("Failed to initialize COM library.");                 //object ppvObject = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_ALL, IID_IActiveDesktop);                 //ActiveDesktop ad = new ActiveDesktop();                 object ad = OLE32DLL.CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_ALL, IID_IActiveDesktop);                 IActiveDesktop iad = (IActiveDesktop)ad;                 if (iad != null)                 {                     //WPSTYLE_CENTER 居中 0                     //WPSTYLE_TILE 平铺 1                     //WPSTYLE_STRETCH 拉伸 2                     //WPSTYLE dwstyle = WPSTYLE.FILL;//这里调整显示背景图片样式                     WALLPAPEROPT wp = new WALLPAPEROPT();                     wp.dwSize = System.Runtime.InteropServices.Marshal.SizeOf(wp);                     wp.dwStyle = dwstyle;                     iad.SetWallpaperOptions(ref wp, 0);                     iad.SetWallpaper(filename, 0);                     iad.ApplyChanges(AD_APPLY.ALL);//AD_APPLY.ALL);                     //System.Runtime.InteropServices.Marshal.ReleaseComObject(ad);                     //ad = null;                 }                 OLE32DLL.CoUninitialize();                 return true;             }             catch             {                 return false;             }         }     }

以上代码也是我从网上流传的代码中复制到的,但是网上流传的代码中其中有一部分代码是有问题的:

1 ActiveDesktop ad = new ActiveDesktop();

就是这里,这个代码不可运行,因为这种接口中IActiveDesktop对象不能通过类型强转得到,因为ActiveDesktop实例本身就不是通过new方式得到的,而我的代码中已经将这个错误进行了修改,并且win10系统中已经确认运行无误。

第三种,IDesktopWallpaper也是一种Com接口(只支持win8以上系统,且支持多显示器独立设置壁纸)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 /// <summary>     /// 使用IDesktopWallpaper方式切换壁纸的方法     /// </summary>     public class DesktopWallpaperCom     {         [ComImport]         [Guid("B92B56A9-8B55-4E14-9A89-0199BBB6F93B")]         [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]         public interface IDesktopWallpaper         {             void SetWallpaper([MarshalAs(UnmanagedType.LPWStr)] string monitorID, [MarshalAs(UnmanagedType.LPWStr)] string wallpaper);               [return: MarshalAs(UnmanagedType.LPWStr)]             string GetWallpaper([MarshalAs(UnmanagedType.LPWStr)] string monitorID);               [return: MarshalAs(UnmanagedType.LPWStr)]             string GetMonitorDevicePathAt(uint monitorIndex);               [return: MarshalAs(UnmanagedType.U4)]             uint GetMonitorDevicePathCount();               [return: MarshalAs(UnmanagedType.Struct)]             Rect GetMonitorRECT([MarshalAs(UnmanagedType.LPWStr)] string monitorID);               void SetBackgroundColor([MarshalAs(UnmanagedType.U4)] uint color);               [return: MarshalAs(UnmanagedType.U4)]             uint GetBackgroundColor();               void SetPosition([MarshalAs(UnmanagedType.I4)] DesktopWallpaperPosition position);               [return: MarshalAs(UnmanagedType.I4)]             DesktopWallpaperPosition GetPosition();               void SetSlideshow(IntPtr items);               IntPtr GetSlideshow();               void SetSlideshowOptions(DesktopSlideshowDirection options, uint slideshowTick);               void GetSlideshowOptions(out DesktopSlideshowDirection options, out uint slideshowTick);               void AdvanceSlideshow([MarshalAs(UnmanagedType.LPWStr)] string monitorID, [MarshalAs(UnmanagedType.I4)] DesktopSlideshowDirection direction);               DesktopSlideshowDirection GetStatus();               bool Enable();         }           [ComImport]         [Guid("C2CF3110-460E-4fc1-B9D0-8A1C0C9CC4BD")]         public class DesktopWallpaper         {         }           [Flags]         public enum DesktopSlideshowOptions         {             None = 0,             ShuffleImages = 0x01         }           [Flags]         public enum DesktopSlideshowState         {             None = 0,             Enabled = 0x01,             Slideshow = 0x02,             DisabledByRemoteSession = 0x04         }           public enum DesktopSlideshowDirection         {             Forward = 0,             Backward = 1         }           public enum DesktopWallpaperPosition         {             Center = 0,             Tile = 1,             Stretch = 2,             Fit = 3,             Fill = 4,             Span = 5,         }           [StructLayout(LayoutKind.Sequential)]         public struct Rect         {             public int Left;             public int Top;             public int Right;             public int Bottom;         }         /// <summary>         /// 获取所有的显示器的ID,用于在设置壁纸中用到的显示器的id         /// </summary>         /// <returns></returns>         public static string[] GetDeskMonitorIds()         {             try             {                 DesktopWallpaper ad = new DesktopWallpaper();                 IDesktopWallpaper iad = (IDesktopWallpaper)ad;                 List<string> mids = new List<string>();                 if (iad != null)                 {                     for (uint i = 0; i < iad.GetMonitorDevicePathCount(); i++)                     {                         mids.Add(iad.GetMonitorDevicePathAt(i));                     }                 }                 System.Runtime.InteropServices.Marshal.ReleaseComObject(ad);                 ad = null;                 return mids.ToArray();             }             catch             {                 return null;             }         }         /// <summary>         /// 新版的win8以上版本调用修改桌面的方法         /// </summary>         /// <param name="filename"></param>         /// <returns></returns>         public static bool SetDesktopWallpaper(string filename, string mid = null)         {             try             {                 DesktopWallpaper ad = new DesktopWallpaper();                 IDesktopWallpaper iad = (IDesktopWallpaper)ad;                 if (iad != null)                 {                     iad.SetWallpaper(mid ?? string.Empty, filename);                 }                 System.Runtime.InteropServices.Marshal.ReleaseComObject(ad);                 ad = null;                 return true;             }             catch             {                 return false;             }         }     }

这是win8系统以上才支持的一种桌面壁纸切换方法,可以支持多显示器独立进行壁纸的设置

最后放上我自己做的壁纸切换工具,可以自适应切换壁纸的方式,且支持多显示器壁纸切换管理和收藏,还有可以添加自动切换壁纸的系统任务,其中的有个vbs脚本是用于壁纸切换的,杀软一般都会报毒,但是要是文件没了就无法切换壁纸了。

下载地址是:https://www.zhaimaojun.cn/P/%e6%a1%8c%e9%9d%a2%e5%a3%81%e7%ba%b8%e7%ae%a1%e7%90%86%e5%99%a8/

以上。

 

     

标签:桌面壁纸,windows,void,csharp,int,MarshalAs,public,string,UnmanagedType
From: https://www.cnblogs.com/webenh/p/18216575

相关文章

  • Windows 迁移至 Linux(debian12) 实验
    〇、前言最近用的Windows出现太多恶性故障,重装系统到怀疑人生,打算彻底抛弃栊子平台了,无法得知是内网被攻击还是细软作祟,反正彻底生气了,不能转换也必须得转换至linux了,宁愿多折腾Linux也不想在闭源的windows上干等干受折磨了。目前大概整理了以下表格,用于替换,之后会进行......
  • Windows系统使用Docker部署Focalboard团队协作工具详细流程
    文章目录前言1.使用Docker本地部署Focalboard1.1在Windows中安装Docker1.2使用Docker部署Focalboard2.安装Cpolar内网穿透工具3.实现公网访问Focalboard4.固定Focalboard公网地址前言本篇文章将介绍如何使用Docker本地部署Focalboard项目管理工具,并且结合cp......
  • Windows中,Jenkins上部署ui自动化自启动浏览器(不使用无头模式)
    1、window上安装jenkins,我是借助以下链接进行安装的:Windows系统下Jenkins安装、配置和使用_jenkinswindows-CSDN博客2、jenkins安装中与github连接:jenkins+github集成自动化测试环境搭建(2)-jenkins+github集成_jenkins自动化测试集成github-CSDN博客3、解决jenkins运行ui......
  • Windows远程桌面是什么?
    Windows远程桌面是一种远程桌面协议,允许用户通过网络连接到远程Windows计算机,并在本地操作远程计算机。它为用户提供了访问远程计算机的便利性,可以在不同地区的电脑或设备之间进行信息远程通信。天联解决方案在远程桌面技术中,天联是一个可靠的解决方案。天联利用组网技术,可......
  • node.js 安装( windows)
    node.js安装(windows10专业版) 1.下载node.js软件;官网下载 地址: 2.cmd中安装 node.js; 用管理员身份 打开cmd,进入想安装的盘符 ,再运行如下  命令  :(版本号 对应自己 下载的 版本号)curl-Ohttps://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi 改成 ......
  • 【安装】VMware虚拟机安装windows操作系统,VM的相关操作
    目录引出报错:pressanykeytobootformcd激活调整显示在VMware上新建虚拟机,并安装Windows1、新建虚拟机2、装载ISO镜像3、安装Windowsserver20164、开机初始化虚拟机操作1、虚拟机基本操作2、虚拟机快照3、虚拟机克隆4、VMwareTools总结引出VMware虚拟......
  • windows下mysql修改表名大消息参数lower_case_table_names,需要initialize才生效
    第一步:尝试修改文件my.ini,发现改了重启不管用:C:\ProgramFiles\MySQL\MySQLServer8.0\bin>notepadmy.ini[mysqld]lower_case_table_names=2 第二步:尝试初始化mysql服务,带上参数。注意,会清空数据库,所以务必先备份数据!!!参考:https://blog.csdn.net/cccgo68/article/d......
  • 翻译《The Old New Thing》- Hotkeys involving the Windows logo key are reserved b
    HotkeysinvolvingtheWindowslogokeyarereservedbythesystem-TheOldNewThing(microsoft.com)https://devblogs.microsoft.com/oldnewthing/20071130-00/?p=24333RaymondChen 2007年11月30日Windows徽标键的热键由系统保留        系统保留了......
  • Windows下安装配置深度学习环境
    Windows下安装配置深度学习环境1.准备工作1.1环境准备操作系统:win1022H2GPU:NvidiaGeForceRTX306012G1.2安装Nvidia驱动、cuda、cuDNN下载驱动需要注册并登录英伟达账号。我这里将下面用到的安装包放到了百度网盘,可以关注微信公众号思......
  • 内网渗透-Windows常用提权方法
    一、前言将介绍常见的提权方法。从为什么该方法能够提权(原理)到使用方法。二、系统内核漏洞提权1.为什么能提权?内核漏洞通常是指内核溢出漏洞,什么溢出呢?缓冲区溢出。那什么是缓冲区溢出呢?当应用程序或者是内核的驱动程序在接受用户输入的数据的时候,它会把这些数据存储在缓冲区......