Skip to content

Instantly share code, notes, and snippets.

@WilbertOnGithub
Created October 13, 2015 07:13
Show Gist options
  • Save WilbertOnGithub/10abbe177bc460f3c20f to your computer and use it in GitHub Desktop.
Save WilbertOnGithub/10abbe177bc460f3c20f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
//PowerInfo.KeepSystemAwake();
Timer aTimer = new Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.ReadLine();
}
private static void OnTimedEvent(object sender, ElapsedEventArgs e)
{
int i = PowerInfo.GetIdleTimeRemaining();
Console.WriteLine(i);
if (i < 1800)
{
Console.WriteLine("Triggering SetExecutionState");
PowerInfo.KeepSystemAwake();
}
}
}
class PowerInfo
{
public static int GetIdleTimeRemaining()
{
var info = new SYSTEM_POWER_INFORMATION();
int ret = GetSystemPowerInformation(SystemPowerInformation, IntPtr.Zero, 0, out info, Marshal.SizeOf(info));
if (ret != 0) throw new System.ComponentModel.Win32Exception(ret);
return info.TimeRemaining;
}
public static void KeepSystemAwake()
{
SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED);
}
private struct SYSTEM_POWER_INFORMATION
{
public int MaxIdlenessAllowed;
public int Idleness;
public int TimeRemaining;
public byte CoolingMode;
}
private const int SystemPowerInformation = 12;
private const int SystemExecutionState = 16;
[DllImport("powrprof.dll", EntryPoint = "CallNtPowerInformation", CharSet = CharSet.Auto)]
private static extern int GetSystemPowerInformation(int level, IntPtr inpbuf, int inpbuflen, out SYSTEM_POWER_INFORMATION info, int outbuflen);
[DllImport("powrprof.dll", EntryPoint = "CallNtPowerInformation", CharSet = CharSet.Auto)]
private static extern int GetSystemExecutionState(int level, IntPtr inpbuf, int inpbuflen, out int state, int outbuflen);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
[Flags]
public enum EXECUTION_STATE : uint
{
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
ES_DISPLAY_REQUIRED = 0x00000002,
ES_SYSTEM_REQUIRED = 0x00000001
// Legacy flag, should not be used.
// ES_USER_PRESENT = 0x00000004
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment