Monday, April 28, 2008

How to Switch-Off the Monitor in C# ?

The desktop monitor can be switched-off programmatically using C#. We make use of Win32 API’s to switch-off the monitor. The programmatic monitor switch-off can be used to switch-off the monitor if the user is not using the computer i.e. if the computer is idle. This may help us save electric power.

As I said earlier we will be using the Win32 API SendMessage defined in user32.dll. In our C# code we will first import the user32.dll and declare the SendMessage function to be used as given below:

[DllImport("user32.dll")]

private static extern int SendMessage(

int hWnd, // handle to destination window
int hMsg, // message
int wParam, // first message parameter
int lParam // second message parameter
);


Parameters:

  • # hWnd (first parameter)
    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.
  • # hMsg (second parameter)
    Specifies the message to be sent (i.e. WM_SYSCOMMAND).
  • # wParam(Third parameter)
    Specifies additional message-specific information (i.e. SC_MONITORPOWER).
  • # lParam (last parameter)
    * 1 - the display is going to low power.
    * 2 - the display is being shut off.
    * –1 - the display is being turned on (undocumented value).

Code to Switch-Off the monitor:

private int SC_MONITORPOWER = 0xF170;

private int WM_SYSCOMMAND = 0x0112;


[DllImport("user32.dll")]

private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);


/// <summary>

/// This method will switch-iff the monitor.

/// </summary>

public void SwitchOffMonitor()

{

SendMessage(this.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 2);

}

///////////////////////////////////////////////////////////////////

3 comments:

pritesh said...

very nice and helpfull. Can you share the complete code here ?

Chris Valmoria said...

How to check if monitor is on?

Chris Valmoria said...

how to check if the monitor is on?

Post a Comment