3
3
using System . IO ;
4
4
using System . Linq ;
5
5
using System . Runtime . InteropServices ;
6
+ using System . Windows ;
6
7
using System . Windows . Media ;
7
8
using System . Windows . Media . Imaging ;
8
9
using Microsoft . Win32 ;
@@ -15,10 +16,16 @@ public static class WallpaperPathRetrieval
15
16
{
16
17
private static readonly int MAX_PATH = 260 ;
17
18
18
- private static readonly Dictionary < DateTime , BitmapImage > wallpaperCache = new ( ) ;
19
+ private static readonly Dictionary < DateTime , ImageBrush > wallpaperCache = new ( ) ;
19
20
20
21
public static Brush GetWallpaperBrush ( )
21
22
{
23
+ // Invoke the method on the UI thread
24
+ if ( ! Application . Current . Dispatcher . CheckAccess ( ) )
25
+ {
26
+ return Application . Current . Dispatcher . Invoke ( GetWallpaperBrush ) ;
27
+ }
28
+
22
29
var wallpaper = GetWallpaperPath ( ) ;
23
30
if ( wallpaper is not null && File . Exists ( wallpaper ) )
24
31
{
@@ -28,7 +35,7 @@ public static Brush GetWallpaperBrush()
28
35
wallpaperCache . TryGetValue ( dateModified , out var cachedWallpaper ) ;
29
36
if ( cachedWallpaper != null )
30
37
{
31
- return new ImageBrush ( cachedWallpaper ) { Stretch = Stretch . UniformToFill } ;
38
+ return cachedWallpaper ;
32
39
}
33
40
34
41
// We should not dispose the memory stream since the bitmap is still in use
@@ -40,8 +47,10 @@ public static Brush GetWallpaperBrush()
40
47
bitmap . DecodePixelHeight = 600 ;
41
48
bitmap . EndInit ( ) ;
42
49
bitmap . Freeze ( ) ; // Make the bitmap thread-safe
43
- wallpaperCache [ dateModified ] = bitmap ;
44
- return new ImageBrush ( bitmap ) { Stretch = Stretch . UniformToFill } ;
50
+ var wallpaperBrush = new ImageBrush ( bitmap ) { Stretch = Stretch . UniformToFill } ;
51
+ wallpaperBrush . Freeze ( ) ; // Make the brush thread-safe
52
+ wallpaperCache . Add ( dateModified , wallpaperBrush ) ;
53
+ return wallpaperBrush ;
45
54
}
46
55
47
56
var wallpaperColor = GetWallpaperColor ( ) ;
0 commit comments