Skip to content

Instantly share code, notes, and snippets.

@spencerhakim
Last active December 23, 2015 20:49
Show Gist options
  • Save spencerhakim/6692445 to your computer and use it in GitHub Desktop.
Save spencerhakim/6692445 to your computer and use it in GitHub Desktop.
Sandman - simple program to immediately put my monitors to sleep when I'm going to bed, and keep them off for a certain amount of time. Got tired of simply waiting for my screens to turn off by themselves (since I never actually put my desktop to sleep), only to be randomly woken up by my mouse shifting a pixel due to some sensor noise or someth…
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace Sandman
{
class Program
{
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, UInt32 wParam, UInt32 lParam);
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
//Values from http://msdn.microsoft.com/en-us/library/windows/desktop/ms646360.aspx
const UInt32 WM_SYSCOMMAND = 0x0112;
const UInt32 SC_MONITORPOWER = 0xF170;
enum SC_MONITORPOWER_LPARAM : uint
{
PoweringOn = unchecked((uint)-1),
LowPower = 1,
PoweringOff = 2
}
static void Main(string[] args)
{
int sleepTime = 3 * 60; //default 3 hours
if( args.Length > 0 )
Int32.TryParse(args[0], out sleepTime);
Console.WriteLine("Hit Ctrl+C to cancel...");
Console.ReadKey(true);
Console.WriteLine( String.Format("Sleeping display(s) for {0} minutes...", sleepTime) );
Thread.Sleep(1500);
//repeatedly send the message, just to make sure no lingering Key Up or accidental/sensor noise mouse movement events accidentally wake the screens
DateTime start = DateTime.UtcNow;
do
{
SendMessage(GetConsoleWindow(), WM_SYSCOMMAND, SC_MONITORPOWER, (uint)SC_MONITORPOWER_LPARAM.PoweringOff);
Thread.Sleep(5000);
}
while( DateTime.UtcNow < start.AddMinutes(sleepTime) );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment