How to turn off your monitor when you lock your machine

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/

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>