These code snippets will show you how to:
- Set the current wallpaper.
- Get the path of the current wallpaper.
- Detect when the current wallpaper changes.
How to set the desktop wallpaper:
using System.Runtime.InteropServices;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SystemParametersInfo(
UInt32 action, UInt32 uParam, String vParam, UInt32 winIni);
private static readonly UInt32 SPI_SETDESKWALLPAPER = 0x14;
private static readonly UInt32 SPIF_UPDATEINIFILE = 0x01;
private static readonly UInt32 SPIF_SENDWININICHANGE = 0x02;
public void SetWallpaper(String path)
{
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
How to get the path of the current desktop wallpaper:
using System.Runtime.InteropServices;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SystemParametersInfo(
UInt32 action, UInt32 uParam, IntPtr vParam, UInt32 winIni);
private static readonly UInt32 SPI_GETDESKWALLPAPER = 0x73;
private static readonly int MAX_PATH = 260;
public String GetWallpaper()
{
String wallpaper = new String('\ 0', MAX_PATH);
SystemParametersInfo(SPI_GETDESKWALLPAPER,
(UInt32)wallpaper.Length, wallpaper, 0);
wallpaper = wallpaper.Substring(0, wallpaper.IndexOf('\ 0'));
return wallpaper;
}
How to detect when the desktop wallpaper changes:
using System.Windows.Forms;
public class MyApp : Form
{
private static readonly UInt32 SPI_SETDESKWALLPAPER = 0x14;
private static readonly UInt32 WM_SETTINGCHANGE = 0x1A;
protected override void WndProc(ref Message message)
{
if (message.Msg == WM_SETTINGCHANGE)
{
if (message.WParam.ToInt32() == SPI_SETDESKWALLPAPER)
{
// Handle that wallpaper has been changed.
}
}
base.WndProc(ref message);
}
}
Of course, you should add return value checking and exception handling where appropriate.
Tags: .NET, C#, Desktop Wallpaper
Sunday, November 2, 2008 at 04:12:02
Thank you for your website
I made with photoshop backgrounds for myspace or youtube and whatever
my backgrounds:http://tinyurl.com/6kw9wq
all the best and thank you again!
Monday, February 9, 2009 at 15:03:14
Thank You.
This is very much useful
Wednesday, April 8, 2009 at 12:14:37
it doesent work for me…
i get these errors:
Error 1 Expected class, delegate, enum, interface, or struct
Error 2 Expected class, delegate, enum, interface, or struct
Error 3 Expected class, delegate, enum, interface, or struct
Error 4 Expected class, delegate, enum, interface, or struct
Error 5 The modifier ‘extern’ is not valid for this item
all errors occur in the dllimport area of the program…