Take the 2-minute tour ×

I want prevent system from going to sleep/hibernate from a windows service. I am calling SetThreadExecutionState function to do that. But it seems to have no effect. I just want to know whether the function SetThreadExecutionState will for windows services. If not what will be the alternative ways to that.

Below is the C# code i am using. I am calling it on Onstart method of service.

static extern uint SetThreadExecutionState(EXECUTION_STATE esFlags);
private void KeepAlive() 
share|improve this question
Is it returning 0? If so, what does GetLastError() return? –  Tony Lee May 3 '11 at 13:39
@Tony Lee It returns a non zero value. –  Prasad May 3 '11 at 13:50
What Windows system did you use? –  Liviu Dec 15 at 13:28

2 Answers 2

up vote 6 down vote accepted

Calling SetThreadExecutionState without ES_CONTINUOUS simply resets the idle timer; to keep the display or system in the working state, the thread must call SetThreadExecutionState periodically.


You need to call this function every now and then. It's not a fire-and-forget.

share|improve this answer
I am including ES_CONTINUOUS flag while calling –  Prasad May 3 '11 at 13:51
@Prasad yes, you are. Call it every 5 minutes with that flag and it will work. –  romkyns May 4 '11 at 21:43
thanks i ve put a timer to do it. It is working now. –  Prasad May 6 '11 at 7:14
So if the periodical call is needed, this means that the MSDN documentation is wrong? Or is this strange 5 minutes phenomenon happening only for services? –  Liviu Dec 15 at 13:38
@Liviu I haven't tested this extensively, but I suspect it's the same for normal programs, not just services. –  romkyns Dec 15 at 17:40

SetThreadExecutionState is only valid for the thread that calls it. If it's called in a worker thread, even with ES_CONTINUOUS, once the worker thread is dead, the setting is not valid anymore and then screen saver will be on again.

Calling this API from a Timer will wake up a worker thread before previous thread is dead and therefore makes it work.

So if you call SetThreadExecutionState in your main thread, like UI thread in client applications, you don't need timer.

share|improve this answer

Your Answer


