change the user's desktop background in csharp

To change the user's desktop background in C#, we can use the SystemParametersInfo function provided by the Windows API. This function allows us to set various system-wide parameters, including the wallpaper.

First, we need to import the required DLL and define the SystemParametersInfo function:

main.cs
using System.Runtime.InteropServices;

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
193 chars
5 lines

Next, we can call the function and pass the path to our desired image as a parameter:

main.cs
private void SetDesktopBackground(string pathToImage)
{
    // specify that we want to set the desktop wallpaper
    const int SET_DESKTOP_BACKGROUND = 20;

    // specify that we want to update the user's profile settings
    const int UPDATE_PROFILE = 1;

    // call the SystemParametersInfo function with the appropriate parameters
    SystemParametersInfo(SET_DESKTOP_BACKGROUND, 0, pathToImage, UPDATE_PROFILE);
}
420 chars
12 lines

Finally, we can call the SetDesktopBackground function with the path to our desired background image:

main.cs
SetDesktopBackground(@"C:\path\to\my\image.jpg");
50 chars
2 lines

gistlibby LogSnag