Click here to Skip to main content
15,867,906 members
Articles / Programming Languages / C#
Tip/Trick

How to lock the PC and power off the display using C#

Rate me:
Please Sign up or sign in to vote.
4.89/5 (17 votes)
17 Oct 2011CPOL2 min read 29.1K   26   4
This article presents an easy and clear way to lock your PC and power off the display using .NET (C#).

Introduction


I have looked for a way to turn off the display when I lock the computer but I only found some solutions that use custom libraries or applications that are running in the background and waiting for the respective event to happen.


I think that these approaches are overcomplicating things so I have written a simple Windows application which does this task by using two APIs from user32.dll.


Background



  1. Managed code can make calls to unmanaged code using the 'DllImport' attribute. [More]
  2. Windows applications are event-driven and use messages to communicate with the system.
    title="About Messages and Message Queues">[More]

Using the code


Locking up the PC can be achieved by calling the LockWorkStation method from 'user32.dll', while powering off the display can be realised by sending the corresponding
Windows message using the PostMessage or SendMessage functions also from 'user32.dll'.


In order to be able to access these functions, the DllImport attribute must be used:


C#
[DllImport("user32.dll")] 
private static extern void LockWorkStation();
[DllImport("user32.dll", SetLastError = true)]
private static extern bool PostMessage(IntPtr hWnd, uint msg,
                      IntPtr wParam, IntPtr lParam);

Now that we have access to them, we can use the PostMessage function to place our message in the queue.
The PostMessage function posts a message in the message queue and returns immediately (unlike SendMessage which waits for the message to be processed).


Here are the parameters needed for shutting off the display:



  1. handler to the window which should receive the msg - set this to broadcast (0xFFFF)
  2. message type - this should be set to system command (0x0112)
  3. wParam - type of system command requested - the needed type is (0xF170), this sets the state of the display
  4. lParam - should be 2 (the display is being shut off).

You can find more information about this type of message
title="More info about WM_SYSCOMMAND message">here
.


C#
private const int WmSyscommand = 0x0112;
private const int ScMonitorpower = 0xF170; 
private const int HwndBroadcast = 0xFFFF;
private const int ShutOffDisplay = 2;

The only thing left to do is calling the function with the previous parameters, as follows :


C#
PostMessage((IntPtr)HwndBroadcast, (uint)WmSyscommand, 
            (IntPtr)ScMonitorpower, (IntPtr)ShutOffDisplay);

Here is everything put together:


C#
namespace Lock_Display
{
    static class Program
    {
        private const int WmSyscommand = 0x0112;
        private const int ScMonitorpower = 0xF170;
        private const int HwndBroadcast = 0xFFFF;
        private const int ShutOffDisplay = 2;
        [DllImport("user32.dll")]
        private static extern void LockWorkStation();
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool PostMessage(IntPtr hWnd, uint msg,
                      IntPtr wParam, IntPtr lParam);
        private static void TurnOffDisplay()
        {
            PostMessage((IntPtr)HwndBroadcast, (uint)WmSyscommand, 
                    (IntPtr)ScMonitorpower, (IntPtr)ShutOffDisplay);
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            LockWorkStation();
            TurnOffDisplay();
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalnice but seems to be working for only desktop applications ?... Pin
Denno.Secqtinstien17-Nov-11 23:28
Denno.Secqtinstien17-Nov-11 23:28 
GeneralReason for my vote of 4 If you had hooked into WindowsKey L ... Pin
jaseRR3-Nov-11 23:42
jaseRR3-Nov-11 23:42 
GeneralReason for my vote of 5 Great Trick, Thanks !! Pin
Sunny_Kumar_1-Nov-11 1:40
Sunny_Kumar_1-Nov-11 1:40 
Reason for my vote of 5
Great Trick, Thanks !!
GeneralReason for my vote of 5 So simple, so helpful. Pin
mavric21224-Oct-11 23:54
mavric21224-Oct-11 23:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.