1
1
using System ;
2
+ using System . Collections . Generic ;
3
+ using System . IO ;
2
4
using System . Linq ;
3
5
using System . Runtime . InteropServices ;
4
- using System . Text ;
5
- using System . Windows . Documents ;
6
6
using System . Windows . Media ;
7
+ using System . Windows . Media . Imaging ;
7
8
using Microsoft . Win32 ;
8
9
using Windows . Win32 ;
9
10
using Windows . Win32 . UI . WindowsAndMessaging ;
@@ -14,7 +15,40 @@ public static class WallpaperPathRetrieval
14
15
{
15
16
private static readonly int MAX_PATH = 260 ;
16
17
17
- public static unsafe string GetWallpaperPath ( )
18
+ private static readonly Dictionary < DateTime , BitmapImage > wallpaperCache = new ( ) ;
19
+
20
+ public static Brush GetWallpaperBrush ( )
21
+ {
22
+ var wallpaper = GetWallpaperPath ( ) ;
23
+ if ( wallpaper is not null && File . Exists ( wallpaper ) )
24
+ {
25
+ // Since the wallpaper file name is the same (TranscodedWallpaper),
26
+ // we need to use the last modified date to differentiate them
27
+ var dateModified = File . GetLastWriteTime ( wallpaper ) ;
28
+ wallpaperCache . TryGetValue ( dateModified , out var cachedWallpaper ) ;
29
+ if ( cachedWallpaper != null )
30
+ {
31
+ return new ImageBrush ( cachedWallpaper ) { Stretch = Stretch . UniformToFill } ;
32
+ }
33
+
34
+ // We should not dispose the memory stream since the bitmap is still in use
35
+ var memStream = new MemoryStream ( File . ReadAllBytes ( wallpaper ) ) ;
36
+ var bitmap = new BitmapImage ( ) ;
37
+ bitmap . BeginInit ( ) ;
38
+ bitmap . StreamSource = memStream ;
39
+ bitmap . DecodePixelWidth = 800 ;
40
+ bitmap . DecodePixelHeight = 600 ;
41
+ bitmap . EndInit ( ) ;
42
+ bitmap . Freeze ( ) ; // Make the bitmap thread-safe
43
+ wallpaperCache [ dateModified ] = bitmap ;
44
+ return new ImageBrush ( bitmap ) { Stretch = Stretch . UniformToFill } ;
45
+ }
46
+
47
+ var wallpaperColor = GetWallpaperColor ( ) ;
48
+ return new SolidColorBrush ( wallpaperColor ) ;
49
+ }
50
+
51
+ private static unsafe string GetWallpaperPath ( )
18
52
{
19
53
var wallpaperPtr = stackalloc char [ MAX_PATH ] ;
20
54
PInvoke . SystemParametersInfo ( SYSTEM_PARAMETERS_INFO_ACTION . SPI_GETDESKWALLPAPER , ( uint ) MAX_PATH ,
@@ -25,7 +59,7 @@ public static unsafe string GetWallpaperPath()
25
59
return wallpaper . ToString ( ) ;
26
60
}
27
61
28
- public static Color GetWallpaperColor ( )
62
+ private static Color GetWallpaperColor ( )
29
63
{
30
64
RegistryKey key = Registry . CurrentUser . OpenSubKey ( @"Control Panel\Colors" , true ) ;
31
65
var result = key ? . GetValue ( "Background" , null ) ;
0 commit comments