Turn your monitor off in C#

I once answered a question on Stack Overflow on how to turn your monitor off in C#.

It seems that the answer no longer worked on Windows 7 en 8. So here is an updated version, which works for me on at least Windows 7.

namespace MonitorOff {

	public enum MonitorState {
		MonitorStateOn = -1,
		MonitorStateOff = 2,
		MonitorStateStandBy = 1
	}

	public partial class Form1 : Form {
		[DllImport("user32.dll")]
		private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);

		public Form1() {
			InitializeComponent();
			SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
		}

		void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e) {
			SetMonitorInState(MonitorState.MonitorStateOff);
		}

		private void button1_Click(object sender, EventArgs e) {
			SetMonitorInState(MonitorState.MonitorStateOff);
		}

		private void SetMonitorInState(MonitorState state) {
			SendMessage(0xFFFF, 0x112, 0xF170, (int)state);
		}
	}
}

As an added bonus I also added some code to turn off your monitor when you lock your machine (need to keep this app running of course).

Leave a Reply