Need to disable the screen saver / screen locking in Windows C#/.Net
theoldnewthing has your answer: Use SetThreadExecutionState(ES_DISPLAY_REQUIRED)
.
This is used by video players and PowerPoint.
SystemParametersInfo with SPI_SETSCREENSAVEACTIVE is the normal way to do this. However, it doesn't disable screen locking.
EDIT - I have an updated answer using the modern Power Availability Request API (supersedes SetThreadExecutionState
) here: https://stackoverflow.com/a/63632916/67824
[FlagsAttribute]
public enum EXECUTION_STATE : uint
{
ES_SYSTEM_REQUIRED = 0x00000001,
ES_DISPLAY_REQUIRED = 0x00000002,
// Legacy flag, should not be used.
// ES_USER_PRESENT = 0x00000004,
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
}
public static class SleepUtil
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
}
public void PreventSleep()
{
if (SleepUtil.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS
| EXECUTION_STATE.ES_DISPLAY_REQUIRED
| EXECUTION_STATE.ES_SYSTEM_REQUIRED
| EXECUTION_STATE.ES_AWAYMODE_REQUIRED) == 0) //Away mode for Windows >= Vista
SleepUtil.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS
| EXECUTION_STATE.ES_DISPLAY_REQUIRED
| EXECUTION_STATE.ES_SYSTEM_REQUIRED); //Windows < Vista, forget away mode
}
Credit: P/Invoke, deadpoint
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS
| EXECUTION_STATE.ES_DISPLAY_REQUIRED
| EXECUTION_STATE.ES_SYSTEM_REQUIRED);
This is not helpful on XP.
In fact, this function is not cross operable between diferent Windows versions (although it works pretty well in Windows Vista or higher)... In Windows XP / 2003 this function shall be called with ES_USER_PRESENT | ES_CONTINUOUS (both should be called)... This will reset periodically both system and display idle timers... In other Windows versions, it's recommended that you use ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED | ES_CONTINUOUS | ES_AWAYMODE_REQUIRED...