Ask Your Question
0

How to stop the screen from going to sleep using C#?

asked 2021-12-04 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-11-11 02:00:00 +0000

djk gravatar image

You can prevent the screen from going to sleep in C# by calling the SetThreadExecutionState method from kernel32.dll. Here's an example:

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
static extern uint SetThreadExecutionState(uint esFlags);

const uint ES_CONTINUOUS = 0x80000000;
const uint ES_SYSTEM_REQUIRED = 0x00000001;

// Prevent screen from going to sleep
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);

// Allow screen to go to sleep again
SetThreadExecutionState(ES_CONTINUOUS);

The first call to SetThreadExecutionState with the ESCONTINUOUS and ESSYSTEMREQUIRED flags will prevent the screen from going to sleep. The second call to SetThreadExecutionState with just the ESCONTINUOUS flag will allow the screen to go to sleep again.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-04 11:00:00 +0000

Seen: 13 times

Last updated: Nov 11 '22