概要
以前、デスクトップの背景画像をC#から変えたくなったことがあるので備忘録としてメモ
検証環境
- Windows 10 Pro
- Visual Studio Enterprise 2019
- .NET Core 3.1
ソースコード
初めにWindows APIを読み込むためにDLLImport
でuser32.dll
を呼びましょう
Program.cs
usingSystem.IO;usingSystem.Runtime.InteropServices;usingSystem.Text;namespaceTestProject{classProgram{[DllImport("user32.dll",CharSet=CharSet.Auto)]publicstaticexternboolSystemParametersInfo(uintuAction,uintuParam,stringlpvParam,uintfuWinIni);privateconstuintSPI_SETDESKWALLPAPER=0x0014;privateconstuintSPIF_UPDATEINIFILE=1;privateconstuintSPIF_SENDWININICHANGE=2;// 壁紙にしたい画像のパスprivatereadonlystaticstringexefolder=Directory.GetCurrentDirectory();privatestaticreadonlyStringBuilderimg=newStringBuilder(@$"{exefolder}\test.png");staticvoidMain(string[]args){SystemParametersInfo(SPI_SETDESKWALLPAPER,0,img.ToString(),SPIF_UPDATEINIFILE|SPIF_SENDWININICHANGE);}}}
SystemParametersInfo
の引数の詳細についてはSystemParametersInfoA functionに記載されています
Note Windows 8 以降のOSは画像を指定する際に絶対パスを指定しなければいけないらしい(すいません確認とれてません)