65.9K
CodeProject 正在变化。 阅读更多。
Home

随机桌面背景更换器

starIconstarIconemptyStarIconemptyStarIconemptyStarIcon

2.00/5 (1投票)

2007年12月8日

CPOL

2分钟阅读

viewsIcon

33316

downloadIcon

370

创建一个程序,可以编程方式地更改背景图像,并将图像转换为BMP格式。

引言

是否曾经苦恼于找不到合适的背景图像?那么,无需再寻找。这个项目将向您展示如何制作一个程序,在您登录时随机选择背景图像,或者让您简单地选择一个背景,或者每分钟到一小时随机选择一个背景。此外,这个项目还包括如何制作图像到BMP转换器的说明。

背景

对VB 2005及更高版本的全面且扎实的了解。

使用代码

Sample Image

在制作或运行此程序之前,请在您的“我的图片”文件夹中创建一个名为“RandomBG”的文件夹,以便URL读取“...\My Pictures\RandomBG”。

首先,启动一个新项目并将其命名为“Random Desktop”。将窗体命名为“frmRD”。现在,创建一个新类并将其命名为“Wallpaper.vb”。 另外创建一个名为“frmConverter”的新窗体。

好的。现在在frmRD上,放置并命名以下属性,使其看起来像顶部的图片

  • PictureBoxPreview
  • ComboBoxstyleComboBox
  • ButtonbtnConverter
  • ButtonbtnPlay
  • ButtonbtnNext”(字体为“Marlett”;要键入箭头,请键入“44”)
  • ButtonbtnRefresh
  • ButtonbtnBackround
  • ListBoxPictureSelection
  • NumericUpDownImageTime
  • CheckBoxCountdownSwitch

frmRD的代码如下

Public Class frmRD

'Variables
    Dim FILE As String
    Dim Delete As Byte
    Dim DIR As String = _
      My.Computer.FileSystem.SpecialDirectories.MyPictures & _
      "\RandomBG\"
    Dim SS As Byte = 0
    Dim IntervalSS As Integer
    Dim RandomImage As Integer
    Dim CurrentImage As Integer
    Dim Max As Integer

    Private Sub frmRD_Load(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MyBase.Load
     
    'On Load, find all files in the My Pictures\RandomBG\ folder
    For Each File As String In My.Computer.FileSystem.GetFiles(_
        My.Computer.FileSystem.SpecialDirectories.MyPictures & "\RandomBG\")
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next

        styleComboBox.DataSource = System.Enum.GetNames(GetType(Wallpaper.Style))
        styleComboBox.SelectedIndex = 2

    'On load, randomly select a background image from the My Pictures\RandomBG\ folder      
    Try
            Max = PictureSelection.Items.Count

            RandomImage = GetRandomNumber(1, Max)

            PictureSelection.SelectedIndex = RandomImage - 1

            FILE = PictureSelection.Text

            Preview.Image = _
              Image.FromFile(My.Computer.FileSystem.SpecialDirectories.MyPictures & _
              "\RandomBG\" & FILE)

            Dim w As Wallpaper = New Wallpaper()
            w.SetWallpaper(My.Computer.FileSystem.SpecialDirectories.MyPictures & _
              "\RandomBG\" & FILE, _
              CType(System.Enum.Parse(GetType(Wallpaper.Style), _
              styleComboBox.Text), Wallpaper.Style))
        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub PictureSelection_MouseClick(ByVal sender As System.Object, _
            ByVal e As System.Windows.Forms.MouseEventArgs) _
            Handles PictureSelection.MouseClick
        
    'Preview an image by clicking it's name in the listbox
    Try
            FILE = PictureSelection.Text

            Preview.Image = Image.FromFile(DIR & FILE)
        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub PictureSelection_MouseDoubleClick(ByVal sender As System.Object, _
                ByVal e As System.Windows.Forms.MouseEventArgs) _
                Handles PictureSelection.MouseDoubleClick
        
    'Remove a file from the list by double clicking it
    PictureSelection.Items.Remove(PictureSelection.SelectedItem)
    End Sub



    Private Sub btnBackround_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnBackround.Click
        
    'Set the currently previewed wallpaper as the background
    Dim w As Wallpaper = New Wallpaper()
        w.SetWallpaper(My.Computer.FileSystem.SpecialDirectories.MyPictures & _
                       "\RandomBG\" & FILE, _
                       CType(System.Enum.Parse(GetType(Wallpaper.Style), _
                       styleComboBox.Text), Wallpaper.Style))
    End Sub

    Private Sub btnRefresh_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles btnRefresh.Click
        
    'Refreshes the listbox, in case new files have been added by the converter
    PictureSelection.Items.Clear()

        For Each File As String In My.Computer.FileSystem.GetFiles(DIR)
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next
    End Sub


    'When the GetRandomNumber(min, max) function is called, 
    'it chooses a random number from the minimum to the maximum specified
#Region "Random Number Generator"
    Private Function GetRandomNumber(ByVal vnMinimumNumber As Integer, _
                     ByVal vnMaximumNumber As Integer)
        Randomize()
        GetRandomNumber = CInt(Int((vnMaximumNumber - _
                            vnMinimumNumber + 1) * Rnd() + vnMinimumNumber))
    End Function
#End Region

    Private Sub btnPlay_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles btnPlay.Click
        
    'Sets up the timers, and prepares the forms vital controls for the auto changer
    If SS = 0 Then
            Counter = ImageTime.Value * 60
            Speed = ImageTime.Value * 60
            IntervalSS = (ImageTime.Value * 60000)
            Slideshow.Interval = IntervalSS
            Countdown.Enabled = True
            Slideshow.Enabled = True
            ImageTime.Enabled = False
            btnBackround.Enabled = False
            styleComboBox.Enabled = False
            btnPlay.Text = "Stop"
            SS = 1
        ElseIf SS = 1 Then
            Slideshow.Enabled = False
            Countdown.Enabled = False
            ImageTime.Enabled = True
            btnBackround.Enabled = True
            styleComboBox.Enabled = True
            btnPlay.Text = "Play"
            SS = 0
        End If
    End Sub

    Private Sub btnNext_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnNext.Click
      
    'Randomly skips ahead one image in the sequence, and sets it as the background  
    Try
            Max = PictureSelection.Items.Count
            CurrentImage = RandomImage
            RandomImage = GetRandomNumber(1, Max)

            If RandomImage = CurrentImage Then
                Exit Sub
            End If

            PictureSelection.SelectedIndex = RandomImage - 1

            FILE = PictureSelection.Text

            Dim w As Wallpaper = New Wallpaper()
            w.SetWallpaper(DIR & FILE, CType(System.Enum.Parse(GetType(Wallpaper.Style), _
                           styleComboBox.Text), Wallpaper.Style))

        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub Slideshow_Tick(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles Slideshow.Tick
        
    'Randomly chooses a new image and applies it every pre-determined tick
    Try
            Max = PictureSelection.Items.Count
            CurrentImage = RandomImage
            RandomImage = GetRandomNumber(1, Max)

            If RandomImage = CurrentImage Then
                Exit Sub
            End If

            PictureSelection.SelectedIndex = RandomImage - 1

            FILE = PictureSelection.Text

            Dim w As Wallpaper = New Wallpaper()
            w.SetWallpaper(DIR & FILE, CType(System.Enum.Parse(GetType(Wallpaper.Style), _
                           styleComboBox.Text), Wallpaper.Style))

        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub btnConvert_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnConvert.Click
        
    'Runs the conversion form
    frmConverter.Show()
        Me.Hide()
    End Sub

    'Variables just for the counter
    Dim Counter As Integer
    Dim Speed As Integer
    Dim Switch As Byte = 0

    Private Sub Countdown_Tick(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Countdown.Tick
        
    'Determines the message when the counter is switched on
    Counter = Counter - 1
        If Switch = 1 Then
            If Counter > 0 Then
                Me.Text = "(" & Counter & " Seconds Remaining)"
            ElseIf Counter = 1 Then
                Me.Text = "(" & Counter & " Second Remaining)"
            ElseIf Counter = 0 Then
                Me.Text = "(" & Counter & " Seconds Remaining)"
                Counter = Speed
            End If
        Else

        End If
    End Sub

    Private Sub CountdownSwitch_CheckedChanged(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles CountdownSwitch.CheckedChanged
     
    'Determines whether the counter is switched on  
    If CountdownSwitch.Checked = True Then
            Switch = 1
        Else
            Switch = 0
            Me.Text = " Random Desktop"
        End If
    End Sub
End Class

Wallpaper”类的代码如下

Imports System
Imports System.Runtime.InteropServices
Imports System.Drawing
Imports Microsoft.Win32

Public Class Wallpaper
    Const SPI_SETDESKWALLPAPER As Integer = 20
    Const SPIF_UPDATEINIFILE As Integer = &H1&
    Const SPIF_SENDWININICHANGE As Integer = &H2&

    <dllimport("user32") /> _
    Public Shared Function SystemParametersInfo(ByVal uAction As Integer, _
           ByVal uParam As Integer, ByVal lpvParam As String, _
           ByVal fuWinIni As Integer) As Integer
    End Function

    Public Enum Style As Integer
        Tiled
        Centered
        Stretched
    End Enum

    Public Sub SetWallpaper(ByVal path As String, ByVal selectedStyle As Style)
        Dim key As RegistryKey = _
          My.Computer.Registry.CurrentUser.OpenSubKey("Control Panel\Desktop", True)

        Select Case selectedStyle
            Case Style.Stretched
                key.SetValue("WallpaperStyle", "2")
                key.SetValue("TileWallpaper", "0")

            Case Style.Centered
                key.SetValue("WallpaperStyle", "1")
                key.SetValue("TileWallpaper", "0")

            Case Style.Tiled
                key.SetValue("WallpaperStyle", "1")
                key.SetValue("TileWallpaper", "1")
        End Select

        SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, _
                             SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)
    End Sub
End Class

Sample Image

我们需要转换器的原因是,Windows XP不允许您将任何类型的图像用于背景,除非是.bmp。通常,当您选择图像作为背景时,Windows会将其转换为.bmp格式,然后使用它。

现在,在frmConverter上,放置并命名以下属性,使其看起来像上面的图片

  • PictureBoxPreview
  • ComboBoxFileType
  • ButtonbtnConvert
  • ButtonbtnFolder
  • ButtonbtnRefresh
  • ListBoxPictureSelection

frmConverter的代码如下

Public Class frmConverter

'Variables for retreving and saving files
    Dim DIR As String = _
      My.Computer.FileSystem.SpecialDirectories.MyPictures & "\"
    Dim FILE As String

    Private Sub btnConvert_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles btnConvert.Click
      
'Saves the selected image as a .bmp to the My Pictures\RandomBG\ directory  
    On Error Resume Next
        Dim d As New System.Drawing.Bitmap(Preview.Image)
        Dim tmp As String = PictureSelection.Text
        tmp = tmp.ToUpper
        If PictureSelection.SelectedIndex < 0 Then
            My.Computer.Audio.Play("C:\Windows\Media\ding.wav")
            Exit Sub
        End If
        tmp = Microsoft.VisualBasic.Replace(UCase(tmp), FileType.Text, "BMP")
        d.Save(My.Computer.FileSystem.SpecialDirectories.MyPictures & _
               "\RandomBG\" & tmp, System.Drawing.Imaging.ImageFormat.Bmp)
        Dim answer As MsgBoxResult
        answer = MsgBox("Are you done converting?", MsgBoxStyle.YesNo)
        If answer = MsgBoxResult.Yes Then
            Me.Close()
        End If
    End Sub

    Private Sub frmConverter_Load(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MyBase.Load
        
    'On Load, Read all the items in the (Default) My Pictures folder to the listbox
    For Each File As String In My.Computer.FileSystem.GetFiles(_
                     My.Computer.FileSystem.SpecialDirectories.MyPictures)
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next
    End Sub

    Private Sub PictureSelection_MouseClick(ByVal sender As System.Object, _
            ByVal e As System.Windows.Forms.MouseEventArgs) _
            Handles PictureSelection.MouseClick
        
    'Preview an image for conversion
    Try
            FILE = PictureSelection.Text

            Preview.Image = Image.FromFile(DIR & FILE)
        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub PictureSelection_MouseDoubleClick(ByVal sender As System.Object, _
                ByVal e As System.Windows.Forms.MouseEventArgs) _
                Handles PictureSelection.MouseDoubleClick
       
        'Double click a file in the listbox to remove it
        PictureSelection.Items.Remove(PictureSelection.SelectedItem)
    End Sub

    Private Sub btnFolder_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles btnFolder.Click
        
        'Select a folder to get images from, (the default is My Pictures)
        FolderBrowser.ShowDialog()
        DIR = FolderBrowser.SelectedPath & "\"

        PictureSelection.Items.Clear()

        For Each File As String In My.Computer.FileSystem.GetFiles(DIR)
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next
    End Sub

    Private Sub btnRefresh_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles btnRefresh.Click
        
        'Refresh the items in the listbox, in case files 
        'have been added to the selected folder
        PictureSelection.Items.Clear()

        For Each File As String In My.Computer.FileSystem.GetFiles(DIR)
            PictureSelection.Items.Add(My.Computer.FileSystem.GetFileInfo(File).Name)
        Next
    End Sub

    Private Sub frmConverter_FormClosing(ByVal sender As System.Object, _
            ByVal e As System.Windows.Forms.FormClosingEventArgs) _
            Handles MyBase.FormClosing
        
        'When the converter closes, frmRD will reapear
        frmRD.Show()
    End Sub
End Class

关注点

这个项目只给我的家庭带来了好处。现在我的父母在登录到他们的计算机时也有了期待的事情。

随机桌面背景更换器 - CodeProject - 代码之家
© . All rights reserved.