SystemSleepAPI.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //************************************************************************
  2. // author: yuzhengyang
  3. // date: 2018.3.9 - 2018.3.9
  4. // desc: 工具描述
  5. // Copyright (c) yuzhengyang. All rights reserved.
  6. // Quote:https://www.cnblogs.com/TianFang/archive/2012/10/12/2721883.html
  7. //************************************************************************
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Runtime.InteropServices;
  12. using System.Text;
  13. namespace Azylee.Core.WindowsUtils.APIUtils
  14. {
  15. public class SystemSleepAPI
  16. {
  17. //定义API函数
  18. [DllImport("kernel32.dll")]
  19. static extern uint SetThreadExecutionState(ExecutionFlag flags);
  20. [Flags]
  21. enum ExecutionFlag : uint
  22. {
  23. System = 0x00000001,
  24. Display = 0x00000002,
  25. Continus = 0x80000000,
  26. }
  27. /// <summary>
  28. /// 阻止系统休眠
  29. /// </summary>
  30. /// <param name="screen">阻止息屏</param>
  31. public static void PreventSleep(bool screen = false)
  32. {
  33. try
  34. {
  35. if (screen)
  36. SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Display | ExecutionFlag.Continus);
  37. else
  38. SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Continus);
  39. }
  40. catch { }
  41. }
  42. /// <summary>
  43. /// 恢复系统休眠和息屏
  44. /// </summary>
  45. public static void ResotreSleep()
  46. {
  47. try { SetThreadExecutionState(ExecutionFlag.Continus); } catch { }
  48. }
  49. /// <summary>
  50. /// 重置系统休眠计时器
  51. /// </summary>
  52. /// <param name="screen">阻止息屏</param>
  53. public static void ResetSleepTimer(bool screen = false)
  54. {
  55. try
  56. {
  57. if (screen)
  58. SetThreadExecutionState(ExecutionFlag.System | ExecutionFlag.Display);
  59. else
  60. SetThreadExecutionState(ExecutionFlag.System);
  61. }
  62. catch { }
  63. }
  64. }
  65. }