none
Application To Select a image and to set it as a wallpaper RRS feed

  • Question

  • U need to have visual Basic / Visual C# 2005 express edition

    This sample application allows you select an image and set it as wallpaper:

    Interacting visually with the Windows Desktop from code is fun, so I decided to see what it would take to change the appearance.  This sample application allows you select an image and set it as wallpaper:

    It turns out that wallpaper is not directly accessible from managed code, but working with Win32 API’s is no problem in this case.  Developing this application allowed me to work with methods imported from system DLL’s, the registry, the file open dialog, a custom enumerated type, and use datasource binding to that enumerated type.

    The application allows you to browse to an image, view a preview (resized smaller to fit if necessary), select the display style (Tiled, Stretched, or Centered), and set the image as the Desktop background.  This enabled me to work some of the new features in Visual Studio 2005 as well.  The code samples shown in this article use Visual C# 2005 Express Edition, however any of the Visual Studio Express Editions can be used to create a similar sample.  Visual Basic source code is also included with the code download for this article. Beta 2 of the Express editions can be downloaded from http://msdn.microsoft.com/express.

    As seen above, the form consists of a button to browse to an image, a button to set the background to that image, a drop-down list of sizing options, and the currently selected image.  Not visible are a SplitContainer control (separating the buttons and ComboBox control from the image) and a file open dialog.  As seen in the ResearchHelp sample, the SplitContainer control is easy to use and allows the user more control over the layout of the user interface.  In the upper panel, the interactive controls have been placed, while the lower space is filled with a docked PictureBox control.

    Desktop wallpaper can use one of three different sizing styles for display.  The Tiled option displays the image at full-size, repeating the image as needed, horizontally and vertically, to fill the screen.  The Stretched option displays the image at whatever size necessary to fill the screen either horizontally or vertically.  Finally, the Centered option places the image at the center of the screen, exactly once, whether if fills the screen or not, even allowing it to go beyond the edges of the screen if it is too large.  In order to support these three styles in an object-oriented way, an enumerated type was created.  This allows us to use the various style options as strongly-typed objects.  This is preferable to string or numeric representations that may not contain valid values and can cause trouble when passed to a method.

    Visual C#

    public enum Style: int
    {
    Tiled, Centered, Stretched
    }

    Visual Basic

    Public Enum Style As Integer
    Tiled
    Centered
    Stretched
    End Enum

    The code that actually sets the image as wallpaper accepts the path to the image and a Style reference.  Two registry values are set in the Control Panel\Desktop key.  Based on which sizing style is requested, numeric codes are set for the WallpaperStyle and TileWallpaper values.  Using an enumerated type for the style means the value is guaranteed to match one of the three defined options -- no default case is needed.

    Visual C#

    RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
    switch( style )
    {
    case Style.Stretched :
    key.SetValue(@"WallpaperStyle", "2") ;
    key.SetValue(@"TileWallpaper", "0") ;
    break;
    case Style.Centered :
    key.SetValue(@"WallpaperStyle", "1") ;
    key.SetValue(@"TileWallpaper", "0") ;
    break;
    case Style.Tiled :
    key.SetValue(@"WallpaperStyle", "1") ;
    key.SetValue(@"TileWallpaper", "1") ;
    break;
    }

    Visual Basic

    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

    At this point, the sizing options have been set, but the actual image path still needs to be set.  The SystemParametersInfo function exists in the user32.dll to allow you to set or retrieve hardware and configuration information from your system.  The function accepts four arguments.  The first indicates the operation to take place, the second two parameters represent data to be set, dependant on requested operation, and the final parameter allows you to specify how changes are saved and/or broadcasted.  The DllImport attribute allows you to specify a DLL, the function to call, and any required arguments.

    Visual C#

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern int SystemParametersInfo(
    int uAction, int uParam, string lpvParam, int fuWinIni);

    Visual Basic

    <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

    In addition to importing the function, you will need to define some constants for use with it.  The first constant represents the wallpaper operation to take place in this sample, to be used in the first argument.  The other two constants will be combined together for the final argument.

    Visual C#

    const int SPI_SETDESKWALLPAPER = 20;
    const int SPIF_UPDATEINIFILE = 0x01;
    const int SPIF_SENDWININICHANGE = 0x02;
    Visual Basic
    Const SPI_SETDESKWALLPAPER As Integer = 20
    Const SPIF_UPDATEINIFILE As Integer = &H1&
    Const SPIF_SENDWININICHANGE As Integer = &H2&

    Once the function is imported, you can call it like any other.  The operation to be invoked is SPI_SETDESKWALLPAPER.  In our sample, the second argument is not needed so set to zero.  The third argument is a reference to the image path.  Note that the image must be in bitmap format.  The final argument specifies that the changes should persist, and also be immediately visible.

    Visual C#

    SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

    Visual Basic

    SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)

    At this point, everything is in place to update the desktop wallpaper.  The user interface provides a Browse button that defaults to the Windows system directory with a *.bmp filter.  About a dozen bitmaps are available here.  The drop-down list is databound to the Style enumerated type by calling the Enum.GetNames() method in the System namespace.  This returns a string array perfect for lists and iteration.

    Visual C#

    styleComboBox.DataSource = System.Enum.GetNames(typeof(Wallpaper.Style));

    Visual Basic

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

    When the user clicks the Set button, the selected ComboBox text must be casted back to the enumerated item object.  Note that this method would throw an exception if an invalid string was passed to it, but this isn’t a risk with a ComboBox.  The conversion occurs as follows:

    Visual C#

    (Wallpaper.Style)Enum.Parse(typeof(Wallpaper.Style), styleComboBox.Text)

    Visual Basic

    CType(System.Enum.Parse(GetType(Wallpaper.Style), styleComboBox.Text),            
    Wallpaper.Style)

    Conclusion

    The Win32 API makes it relatively easy to take advantage of features that aren’t available in the .NET Framework.  A nice addition would be to use the Save() method of the Bitmap class to automatically convert images to Bitmap format so a user could select JPEG or GIF images from the local hard drive.  Download Visual C# 2005 Express Edition or Visual Basic 2005 Express Edition and give this application a try.  Get started at http://msdn.microsoft.com/express.  


    Tuesday, April 24, 2007 2:56 AM