Thursday, November 22, 2012

C# How to keep your system from entering sleep mode when running long programs


//Need to include the System.Runtime.InteropServices in order to use the [DllImport] attribute
using System.Runtime.InteropServices;

namespace MyAmazingProgram
{
    public class MyApplication
    {

         //Enable away mode and prevent the sleep idle time-out. For more information read here. http://msdn.microsoft.com/en-us/library/aa373208%28v=vs.85%29.aspx
        SystemState.SetThreadExecutionState(SystemState.ES_CONTINUOUS | SystemState.ES_SYSTEM_REQUIRED | SystemState.ES_AWAYMODE_REQUIRED);
         
        //Execute long running code here...
        // Clear EXECUTION_STATE flags to disable away mode and allow the system to idle to sleep normally.
        SystemState.SetThreadExecutionState(SystemState.ES_CONTINUOUS);
     

    }  
    internal static class SystemState
    {
        // Import SetThreadExecutionState Win32 API and all flags
        [DllImport("kernel32.dll")]
        public static extern uint SetThreadExecutionState(uint esFlags);

        public const uint ES_SYSTEM_REQUIRED = 0x00000001;
        public const uint ES_DISPLAY_REQUIRED = 0x00000002;
        public const uint ES_USER_PRESENT = 0x00000004;
        public const uint ES_AWAYMODE_REQUIRED = 0x00000040;
        public const uint ES_CONTINUOUS = 0x80000000;
    }
}