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
46
47
48
49
50
51
52
53
54
55
#Full code can be found in zip folder. The code below 
#is the class in charge of changing the background.
 
require 'Win32API'
 
class DesktopChangerManager
  
  @@Allowed_Extentions = Regexp.new('\.(jpg|jpeg|bmp)'true)
  @@Save_File = "last-config.txt"
  
  attr_reader :dir_path
  
  def self.Save_File
    @@Save_File
  end
  
  def self.Allowed_Extentions
    @@Allowed_Extentions
  end
  
  def initialize(directory)
    @dir_path = directory
    srand Time.now.to_i
  end
  
  def change_dir(directory)
    @dir_path = directory
  end
  
  def next_image
    possible_desktops = Dir.entries(dir_path).select { |file_name| @@Allowed_Extentions =~ file_name }
    file_count = possible_desktops.length
 
    return -1 if file_count < 1
    
    selected_file = ""
    #Ensure that we only select images from the folder.
    while (selected_file.empty?)
      selection = rand(file_count)
      selected_file = possible_desktops[selection]
    end
    
    DesktopChangerManager.change_background( @dir_path + selected_file )
  end
 
  def DesktopChangerManager.change_background(full_path)
    desktop = Win32API.new("user32""SystemParametersInfo"['L','L','P','L'] , 'L')
    desktop.Call(20,0,full_path,0)
  end
  
  def save
    File.open(@@Save_File, File::WRONLY|File::TRUNC|File::CREAT) { |f| f<<@dir_path }
  end
 
end