How to get the current windows wallpaper in C#

Being able to make software is great. Not only because you can make a living from it, but also because it helps you in everyday life. Like when you have to manage your 10k+ wallpaper library. I for once always get baited by these “575 awesome wallpapers you absolutely need” posts and download them right away into my library. Every now and then a black sheep sneaks in but i only see it after it pops up on my Desktop (as if i would review all of these 575 wallpapers).

And here it comes together: as a software developer i have the means to write a small piece of code that gets rid of these ugly wallpapers.

So i hacked this snippet that moves the current wallpaper out of its current folder and into a “reject” folder.
The current wallpaper path can be found in a registry entry “TranscodedImageCache” in “HKCU\Control Panel\Desktop” (at least in Windows 8.1). It’s encoded with unicode though and has to be cleaned a little bit.

See yourself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
 
namespace WallpaperRejecter
{
    class Program
    {
        // Source: http://stackoverflow.com/a/406576/441907
        static byte[] SliceMe(byte[] source, int pos)
        {
            byte[] destfoo = new byte[source.Length - pos];
            Array.Copy(source, pos, destfoo, 0, destfoo.Length);
            return destfoo;
        }
 
        public void run(String wallpaperDir)
        {
            byte[] path = (byte[])Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop").GetValue("TranscodedImageCache");
            String wallpaper_file = Encoding.Unicode.GetString(SliceMe(path, 24)).TrimEnd("\0".ToCharArray());
            String reject_dir = wallpaperDir + "_rejects";
            String new_path = reject_dir + "\\" + Path.GetFileName(wallpaper_file);
 
            if (!System.IO.Directory.Exists(reject_dir))
            {
                System.IO.Directory.CreateDirectory(reject_dir);
            }
 
            File.Move(wallpaper_file, new_path);
            Console.WriteLine("Moved file: " + wallpaper_file + " to " + new_path);
 
            Console.ReadLine();
        }
 
        static void Main(string[] args)
        {
            new Program().run(@"G:\Downloads\Wallpapers");
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *