-2

I need to set the background of a Windows form to the user's current Desktop wallpaper. How do I do this in C#? Thanks

Apollo199999999
  • 186
  • 3
  • 12
  • Mate, show us your code and we can help you to fix your code. – AFetter Mar 17 '19 at 08:52
  • a quick google search, and I found this, I have used it before. https://stackoverflow.com/questions/1061678/change-desktop-wallpaper-using-code-in-net – traveler3468 Mar 17 '19 at 09:54
  • AndrewE the page you have linked is about changing the desktop wallpaper, and not about setting a winform background to be the same as the desktop wallpaper. – Apollo199999999 Mar 18 '19 at 09:18

1 Answers1

4

You can try the following code. I've tested this code on windows 8 and it works for me:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StringFormatting
{
    public partial class WallpaperTest : Form
    {
        private const UInt32 SPI_GETDESKWALLPAPER = 0x73;
        private const int MAX_PATH = 260;
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SystemParametersInfo(UInt32 uAction, int uParam, string lpvParam, int fuWinIni);

        public WallpaperTest()
        {
            InitializeComponent();
            this.BackgroundImage = GetCurrentDesktopWallpaper();
            this.BackgroundImageLayout = ImageLayout.Stretch; 
        }

        public Image GetCurrentDesktopWallpaper()
        {
            string currentWallpaper = new string('\0', MAX_PATH);
            SystemParametersInfo(SPI_GETDESKWALLPAPER, currentWallpaper.Length, currentWallpaper, 0);
            string imageAddress = currentWallpaper.Substring(0, currentWallpaper.IndexOf('\0'));
            return Image.FromFile(imageAddress); 
        }


    }
}
Navid Rsh
  • 308
  • 1
  • 6
  • 14