Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Allow sleeping and monitor disabling in Windows standalone

Discussion in 'Editor & General Support' started by CorruptScanline, Jul 16, 2015.

  1. CorruptScanline

    CorruptScanline

    Joined:
    Mar 26, 2009
    Posts:
    217
    I need to prevent a Windows (and Mac in the future) standalone build from keeping the computer awake and the monitor turned on while it has focus.

    Screen.sleepTimeout does not work on PC standalone builds and I have reported it as a bug.

    I am unable to disable the built in sleep prevention implemented in windows standalone builds.

    I am attempting to disable it using windows API calls:
    Code (CSharp):
    1.  
    2. static public class SleepUtil
    3. {
    4.     [DllImport("kernel32.dll")]
    5.     static private extern uint SetThreadExecutionState(uint esFlags);
    6.     static private uint ES_CONTINUOUS = 0x80000000;
    7.     static private uint ES_SYSTEM_REQUIRED = 0x00000001;
    8.     static private uint ES_DISPLAY_REQUIRED = 0x00000002;
    9.        
    10.     static public void AllowSleep()
    11.     {
    12.         uint previous = SetThreadExecutionState(ES_CONTINUOUS);
    13.         if (previous == 0)
    14.         {
    15.             throw new System.Exception("SetThreadExecutionState failed.");
    16.         }
    17.     }
    18. }
    19.  
    When calling AllowSleep() on the main thread when the standalone build starts up, the build still keeps the monitor on and the computer from sleeping. I have also tried calling it in OnApplicationFocus and Update loop with the same results.

    Does anyone have any ideas for why this wouldn't be working?
     
  2. bhaunitybuild

    bhaunitybuild

    Joined:
    Jun 5, 2019
    Posts:
    1
    Long shot, but did you ever get this working?