C#/WPF - Monitor Switcher

There are many situations where I want to turn my monitor off without putting my system into standby. For example, at night, I keep my system running to record shows on my Media Center, so I would want my monitors to turn off immediately. Manually turning them on/off by pushing their buttons isn’t a very efficient solution.

So, instead, I created an application that turns the monitor off at the push of a virtual button and turns them back on when the mouse moves. Here is how my application looks:

You can install and run the application (XP/Vista) by clicking here: http://www.kirupafx.com/MonitorSwitcher/MonitorSwitcher.application

Because accessing the monitor requires lower-level Win32 calls, I used some resources on http://www.pinvoke.net to create a SendMessage call to access the monitor’s On/Off state. The code is:

using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Runtime.InteropServices;
using System.Windows.Input;
namespace MonitorSwitcher
{
 public partial class Window1
 {
        [DllImport("user32.dll")]
        public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);
        const int SC_MONITORPOWER = 0xF170;
        const int WM_SYSCOMMAND = 0x0112;
        const int MONITOR_ON = -1;
        const int MONITOR_OFF = 2;
        const int MONITOR_STANBY = 1;
        int onFlag = 0;
  public Window1()
  {
   this.InitializeComponent();
  }
        private void MonitorOff(object sender, RoutedEventArgs e)
        {
            SendMessage(-1, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);
            onFlag = 1;
        }
        private void MonitorOn(object sender, MouseEventArgs e)
        {
            if (onFlag == 1)
            {
                SendMessage(-1, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_ON);
                onFlag = 0;
            }
        }
 }
}

I have attached the full source file for this below :slight_smile:

Cheers!
Kirupa :bandit: