Tag Archives: HWND_BROADCAST
Turn monitor on/off in C#
The following snippet will allow you to change your monitor’s state to either off/on or standby mode. Unlike other methods this one works on Windows 7 as well (tested under Windows 7 64bit).
The first step is to include in your class the following code:
1 2 3 4 5 6 7 8 9 10 11 12 | [DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); private int SC_MONITORPOWER = 0xF170; private int WM_SYSCOMMAND = 0x0112; enum MonitorState { ON = -1, OFF = 2, STANDBY = 1 } |
This will allow us to send a WM_SYSCOMMAND
message using SendMessage
to alter the state of the monitor.
Finally, add the method which we will be calling when we want to change the monitor’s state:
1 2 3 4 | public void SetMonitorState(MonitorState state) { SendMessage(this.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, (int)state); } |
Simply call the SetMonitorState
method with the desirable state you want to change your monitor’s state to.
Usage:
1 | SetMonitorState(MonitorState.OFF); |
Keep in mind that the SC_MONITORPOWER
commands supports devices that have power-saving features, so depending on the monitor’s brand/drivers/firmware results might vary.
Posted in C#.
Tagged C#, csharp, HWND_BROADCAST, monitor, SC_MONITORPOWER, snippet, winforms, WM_SYSCOMMAND