- 1 year ago
Set wallpaper on primary/secondary monitor only
To set the wallpaper on a specific monitor, you can use the SystemParametersInfo
function in Windows API. Here's an example in C#:
csharpusing System;
using System.Runtime.InteropServices;
public class WallpaperChanger
{
private const int SPI_SETDESKWALLPAPER = 20;
private const int SPIF_UPDATEINIFILE = 0x01;
private const int SPIF_SENDCHANGE = 0x02;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper(string wallpaperPath, bool primaryMonitorOnly)
{
int monitorIndex = primaryMonitorOnly ? 1 : 2;
string parameter = $"{wallpaperPath},{monitorIndex}";
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, parameter, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
}
}
class Program
{
static void Main()
{
// Example usage:
WallpaperChanger.SetWallpaper("C:\\path\\to\\wallpaper.jpg", primaryMonitorOnly: true);
}
}
In this example, the SetWallpaper
method takes two parameters: the path to the wallpaper image file and a boolean flag primaryMonitorOnly
indicating whether to set the wallpaper on the primary monitor only. If primaryMonitorOnly
is true
, the wallpaper will be set on the primary monitor; otherwise, it will be set on the secondary monitor.
The SetWallpaper
method uses the SystemParametersInfo
function to set the wallpaper. It passes the SPI_SETDESKWALLPAPER
action code and the monitorIndex
(1 for primary, 2 for secondary) as the parameters.
Note that this example is in C#, but you can use the same SystemParametersInfo
function in other languages by importing it from the appropriate Windows API library.