Advertisement
Guest User

Untitled

a guest
Oct 13th, 2015
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Timers;
  8.  
  9. namespace ConsoleApplication6
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. //PowerInfo.KeepSystemAwake();
  16.  
  17. Timer aTimer = new Timer();
  18. aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
  19. aTimer.Interval = 5000;
  20. aTimer.Enabled = true;
  21. Console.ReadLine();
  22. }
  23.  
  24. private static void OnTimedEvent(object sender, ElapsedEventArgs e)
  25. {
  26. int i = PowerInfo.GetIdleTimeRemaining();
  27. Console.WriteLine(i);
  28.  
  29. if (i < 1800)
  30. {
  31. Console.WriteLine("Triggering SetExecutionState");
  32. PowerInfo.KeepSystemAwake();
  33. }
  34. }
  35. }
  36.  
  37. class PowerInfo
  38. {
  39. public static int GetIdleTimeRemaining()
  40. {
  41. var info = new SYSTEM_POWER_INFORMATION();
  42. int ret = GetSystemPowerInformation(SystemPowerInformation, IntPtr.Zero, 0, out info, Marshal.SizeOf(info));
  43. if (ret != 0) throw new System.ComponentModel.Win32Exception(ret);
  44. return info.TimeRemaining;
  45. }
  46.  
  47. public static void KeepSystemAwake()
  48. {
  49. SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED);
  50. }
  51.  
  52. private struct SYSTEM_POWER_INFORMATION
  53. {
  54. public int MaxIdlenessAllowed;
  55. public int Idleness;
  56. public int TimeRemaining;
  57. public byte CoolingMode;
  58. }
  59. private const int SystemPowerInformation = 12;
  60. private const int SystemExecutionState = 16;
  61. [DllImport("powrprof.dll", EntryPoint = "CallNtPowerInformation", CharSet = CharSet.Auto)]
  62. private static extern int GetSystemPowerInformation(int level, IntPtr inpbuf, int inpbuflen, out SYSTEM_POWER_INFORMATION info, int outbuflen);
  63. [DllImport("powrprof.dll", EntryPoint = "CallNtPowerInformation", CharSet = CharSet.Auto)]
  64. private static extern int GetSystemExecutionState(int level, IntPtr inpbuf, int inpbuflen, out int state, int outbuflen);
  65.  
  66. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  67. static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
  68. [Flags]
  69. public enum EXECUTION_STATE : uint
  70. {
  71. ES_AWAYMODE_REQUIRED = 0x00000040,
  72. ES_CONTINUOUS = 0x80000000,
  73. ES_DISPLAY_REQUIRED = 0x00000002,
  74. ES_SYSTEM_REQUIRED = 0x00000001
  75. // Legacy flag, should not be used.
  76. // ES_USER_PRESENT = 0x00000004
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement