14

I am writing an application in C# that plays a movie. I need to figure out how to disable the screen saver and power options using C#.

I know the Windows SDK API has a function called SetThreadExecutionState() which can be used to do this, however, I do not know if there is a better way to do it. If not, how do I incorporate this function into C#?

Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • What if you just prevented the screen saver/power options from activating (e.g. send a key stroke to the OS every N seconds)? – fre0n Feb 17 '10 at 21:55
  • Yes. I found a pretty nice class in C# here: http://www.codeproject.com/KB/cs/ScreenSaverControl.aspx – Icemanind Mar 01 '10 at 22:34
  • I found a solution here: http://www.codeproject.com/KB/cs/ScreenSaverControl.aspx – Icemanind Mar 01 '10 at 22:34

1 Answers1

18

Not sure if there is a better .NET solution but here is how you could use that API:

The required usings:

using System.Runtime.InteropServices;

The P/Invoke:

public const uint ES_CONTINUOUS = 0x80000000;
public const uint ES_SYSTEM_REQUIRED = 0x00000001;
public const uint ES_DISPLAY_REQUIRED = 0x00000002;

[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint SetThreadExecutionState([In] uint esFlags);

And then disable screensaver by:

SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED);

Finnaly enable screensaver by reseting the execution state back to original value:

SetThreadExecutionState(ES_CONTINUOUS);

Note that I just picked one of the flags at random in my example. You'd need to combine the correct flags to get the specific behavior you desire. You will find the description of flags on MSDN.

Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
Cory Charlton
  • 8,868
  • 4
  • 48
  • 68
  • http://stackoverflow.com/questions/241222/need-to-disable-the-screen-saver-screen-locking-in-windows-c-net – user1005462 Oct 06 '15 at 12:30
  • 6
    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED); - work perfect on win10 – user1005462 Oct 06 '15 at 12:32
  • @user1005462 what's the `uint` value for `ES_SYSTEM_REQUIRED` ?? – mrid Mar 10 '19 at 09:48
  • so i want to make app only for me, which disallow pc to go to sleep. One big button "DONT SLEEP", and then big button to disactivate it. What are values which allows pc to go to bed? – Kamil Aug 26 '19 at 17:12
  • flag values can be found here: https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate – IdontCareAboutReputationPoints May 24 '21 at 06:40
  • The docs (https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate#remarks) explicitly say: "This function does not stop the screen saver from executing." – Jonas Kohl Aug 03 '22 at 07:42