Standby.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace MediaBrowser.ServerApplication.Native
  4. {
  5. /// <summary>
  6. /// Class NativeApp
  7. /// </summary>
  8. public static class Standby
  9. {
  10. public static void PreventSleepAndMonitorOff()
  11. {
  12. NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED | NativeMethods.ES_DISPLAY_REQUIRED);
  13. }
  14. public static void PreventSleep()
  15. {
  16. NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
  17. }
  18. // Clear EXECUTION_STATE flags to allow the system to sleep and turn off monitor normally
  19. public static void AllowSleep()
  20. {
  21. NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS);
  22. }
  23. internal static class NativeMethods
  24. {
  25. // Import SetThreadExecutionState Win32 API and necessary flags
  26. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  27. public static extern uint SetThreadExecutionState(uint esFlags);
  28. public const uint ES_CONTINUOUS = 0x80000000;
  29. public const uint ES_SYSTEM_REQUIRED = 0x00000001;
  30. public const uint ES_DISPLAY_REQUIRED = 0x00000002;
  31. }
  32. [Flags]
  33. internal enum EXECUTION_STATE : uint
  34. {
  35. ES_NONE = 0,
  36. ES_SYSTEM_REQUIRED = 0x00000001,
  37. ES_DISPLAY_REQUIRED = 0x00000002,
  38. ES_USER_PRESENT = 0x00000004,
  39. ES_AWAYMODE_REQUIRED = 0x00000040,
  40. ES_CONTINUOUS = 0x80000000
  41. }
  42. }
  43. }