How to set Bing wallpaper as your desktop wallpaper

Standard

This post is about setting Bing wallpaper as your desktop wallpaper using C# and Windows Forms. Bing.com is famous for having some nice pictures as wallpaper, updated on daily basis. The Bing Desktop application comes with same feature. Here is the code snippet, which has two parts one, download the wallpaper image from bing.com and set it as wallpaper using WIN32 APIs.

The URL for getting wallpaper is used by bing WP7 application.

http://appserver.m.bing.net/BackgroundImageService/TodayImageService.svc/GetTodayImage?dateOffset=0&urlEncodeHeaders=true&osName=wince&osVersion=7.10&orientation=480×800&deviceName=WP7Device&mkt=en-US&AppId=1

In the URL, you can change the orientation to 1024×768, landscape mode in Windows Phone to get the wallpaper. And the mkt parameter specifies the region, I am keep it as en-US. The following snippet will download the wallpaper and save it in the Temp folder as wallpaper.bmp. The SetWallpaper function will set the wallpaper.bmp as desktop wallpaper using Win32 API.

WebClient webClient = new WebClient();
webClient.OpenReadCompleted += (o, ev) =>
{
    if (ev.Error == null)
    {
        var wallpaper = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
        using (var bitmap = Bitmap.FromStream(ev.Result))
        {
            bitmap.Save(wallpaper, ImageFormat.Bmp);
            SetWallpaper(wallpaper);
        }
    }
};

webClient.OpenReadAsync(new Uri(bingserviceUrl));

Here is the SetWallpaper method

private static void SetWallpaper(string wallpaper)
{
    RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
    key.SetValue(@"WallpaperStyle", 2.ToString());
    key.SetValue(@"TileWallpaper", 0.ToString());

    SystemParametersInfo(SPI_SETDESKWALLPAPER,
        0, wallpaper,
        SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}

You require following WIN32 API declarations as well.

const int SPI_SETDESKWALLPAPER = 20;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;

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

In the SetWallpaper function, I am setting the wallpaper picture position as Stretched. You can change this by changing the WallpaperStyle and TileWallpaper values.

Picture Position WallpaperStyle TileWallpaper
Stretched 2 0
Centered 1 0
Tiled 1 1
Fit* 6 0
Fill* 10 0
* – Windows 7 and later

Happy Programming :)

How to move a window or form without titlebar

Standard

In my current project I had to implement move for a Form, which doesn’t have a title bar or FormBorderStyle property set to None. Instead of title bar I was using a Panel with background Image. Here is the code snippet.

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, 
int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();

private void TitlePanel_MouseDown(object sender, MouseEventArgs e)
{
    ReleaseCapture();
    SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}

As it is WIN32 API call, you need to import System.Runtime.InteropServices namespace.

How to lock system using C#

Standard

Another WIN32 API tip helps to lock your system from C# code. It is very straight forward API. You can find this more information about LockWorkStation function from MSDN.

Here is the WIN32 API declaration.

[DllImport("user32.dll", SetLastError = true)]
static extern bool LockWorkStation();

And here is the implementation.

if (!LockWorkStation())
{
    throw new Win32Exception(Marshal.GetLastWin32Error());
}

Happy Coding :)

How to turn off your monitor when you lock your machine

Standard

Usually we forgot to turn off monitor, when we lock our computer. It is a good thing, to save energy. You can configure your operating system to turn off monitor after sometime. But sometimes you may change/ disable this setting and forgot to re-enable it. Here is a code snippet, which will turn off your monitor, while you lock your system. To get the System Lock event, you need to subscribe SessionSwitch event in SystemEvents class. SystemEvents class provides access to system event notifications. And the sessionswitch event occurs when the currently logged-in user has changed. You can find more details about SystemEvents class in MSDN. To turn off monitor combination off SendMessage and HWND_BROADCAST API calls are used. Here is a post about How to turn off monitor programmatically using C#.

And here is the code snippet.


using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Win32;

public partial class Form1 : Form
{
    private const int HWND_BROADCAST = 0xFFFF;
    private const int SC_MONITORPOWER = 0xF170;
    private const int WM_SYSCOMMAND = 0x112;

    private const int MONITOR_ON = -1;
    private const int MONITOR_OFF = 2;
    private const int MONITOR_STANBY = 1;

    [DllImport("user32.dll")]
    private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);

    public Form1()
    {
        InitializeComponent();
        //Subscribe for SessionSwith event
        SystemEvents.SessionSwitch += new SessionSwitchEventHandler((sender, e) =>
        {
            if (e.Reason == SessionSwitchReason.SessionLock)
            {
                //If Reason is Lock, Turn off the monitor.
                SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);
            }
        });
    }
}

This can be used in a Windows Forms or WPF application.

Happy Programming :)

Update: Find this application on codeplex : http://powersave.codeplex.com/