Monitor control through
While just taking part in the routine online discussions, I came across this nice article which gave a complete explaination on how to control the monitor through code. Although the article was not meant for first timers, I took some time out to reformat and present the same content here so that anyone could read and understand.
The Monitor can be controlled by the SendMessage API. This is not a .NET API, hence we must delve into P/Invoke and COM Interop.. but dont worry, I wil keep it simple.
To use the interop functionality, you must first include the reference
using System.Runtime.InteropServices;
Then comes the DllImport using which we import the library that contains the SendMessage API – user32.dll
[DllImport("user32.dll")]
Then declare the SendMessage function
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
The parameters represent the following data:
- hWnd – Handle to the window whose window procedure will receive the message. Should be a valid Windows handler
- Msg – specifies the message to be sent
- wParam – specifies additional message-specific information
- lParam – specifies monitor state
hWnd can be set to the current window handle if it is a Windos Forms application using
this.Handle;
But if it is a Console app of a class lib, then you would be better off setting it to -1. (Which sets the handle to the top level window in the system.)
Msg will be set to a predefined value of 0x0112. Even wParam will be set to a predefined value of 0xF170. I shall name the constants so as to avoid confusion.
const int WM_SYSCOMMAND = 0x0112;
const int SC_MONITORPOWER = 0xF170;
lParam specifies the monitor state. It has 3 states – ON, OFF and STANDBY with corresponding values -1, 2 and 1.
Hence a call to turn the monitor off would read something like this in a console application:
SendMessage((IntPtr) (-1), WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr) 2);
Download the sample source code here.