Wednesday, January 7, 2009

Switch ON and OFF the monitor

How to turn off your monitor via code?
This is an important question at least to me , because I use my computer for long time daily and frequently turn on and off the screen as a way to save energy and power .
I hate to make that by using the monitor button(off/on) , because I hear sound from the monitor feel me that the screen may damage .
So I will inform you here , How to turn off your monitor via code ( C# ) ?

I will code that depending in API called SendMessage function it’s useful to handle monitor states - the display is going to low power, the display is being shut off and the display is turned on .

Syntax :
LRESULT SendMessage( HWND hWnd, UINT Msg,WPARAM wParam, LPARAM lParam );


Parameters:
  • # HWnd (first paramter)
    Handle to the window whose window procedure will receive the message. If you don't want to bother creating a window to send the message to, you can send the message to all top level windows (HWND_BROADCAST) or you can use GetDesktopWindow function sending the message to the desktop window.
  • # Msg (second paramter)
    Specifies the message to be sent (WM_SYSCOMMAND).
  • # wParam(Third paramter)
    Specifies additional message-specific information (SC_MONITORPOWER).
  • # LParam (last paramter)
    * 1 - the display is going to low power.
    * 2 - the display is being shut off.
    * –1 - the display is being turned on (undocumented value).

Start the coding now :

First of all you should use
using System.Runtime.InteropServices; //to DllImport

public int WM_SYSCOMMAND = 0x0112;
public int SC_MONITORPOWER = 0xF170; //Using the system pre-defined MSDN constants that can be used by the SendMessage() function .


[DllImport("user32.dll")]
private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
//To call a DLL function from C#, you must provide this declaration .


private void button1_Click(object sender, System.EventArgs e)
{

SendMessage( this.Handle.ToInt32() , WM_SYSCOMMAND , SC_MONITORPOWER ,2 );//DLL function
}

Ref:- http://fci-h.blogspot.com/2007/03/turn-off-your-monitor-via-code-c.html