如何防止Windows进入空闲状态?

use*_*789 43 c# windows

我正在开发一个C#应用程序,它在后台运行,没有任何Windows控件.

我想通知Windows我的应用程序仍处于活动状态,以防止Windows进入空闲状态.

是否有任何API可以从我的应用程序调用,通知Windows操作系统我的应用程序仍然存在?

提前致谢.

Joa*_*oao 41

您将使用SetThreadExecutionState函数.像这样的东西:

public partial class MyWinForm: Window
{
    private uint fPreviousExecutionState;

    public Window1()
    {
        InitializeComponent();

        // Set new state to prevent system sleep
        fPreviousExecutionState = NativeMethods.SetThreadExecutionState(
            NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
        if (fPreviousExecutionState == 0)
        {
            Console.WriteLine("SetThreadExecutionState failed. Do something here...");
            Close();
        }
    }

    protected override void OnClosed(System.EventArgs e)
    {
        base.OnClosed(e);

        // Restore previous state
        if (NativeMethods.SetThreadExecutionState(fPreviousExecutionState) == 0)
        {
            // No way to recover; already exiting
        }
    }
}

internal static class NativeMethods
{
    // Import SetThreadExecutionState Win32 API and necessary flags
    [DllImport("kernel32.dll")]
    public static extern uint SetThreadExecutionState(uint esFlags);
    public const uint ES_CONTINUOUS = 0x80000000;
    public const uint ES_SYSTEM_REQUIRED = 0x00000001;
}
Run Code Online (Sandbox Code Playgroud)

  • @Alessio - 返回"0"表示方法失败.从'SetThreadExecutionState`的文档 - "如果函数成功,返回值是先前的线程执行状态.如果函数失败,返回值为NULL." (注意 - 我假设您可能已经想到了这一点,但想要发布完整性的答案,并帮助其他可能出现并查看您的评论的人) (5认同)
  • 可能是我,但这似乎不适用于Windows 10 (2认同)
  • 在Win 10 @ecklerpa为我工作。另外,如果有人需要这样做以获取可见的外观,还请记住设置ES_DISPLAY_REQUIRED以避免显示器关闭。 (2认同)

Gus*_*ori 19

你有几个选择:

  • 使用SetThreadExecutionState,其中:

    允许应用程序通知系统它正在使用中,从而防止系统在应用程序运行时进入睡眠状态或关闭显示屏.

    你可以在哪里用ES_SYSTEM_REQUIRED旗帜

    通过重置系统空闲计时器强制系统处于工作状态.

  • 使用SendInput伪造击键,鼠标移动/点击

  • 另一种方法是将您的应用程序更改为Windows服务.

SetThreadExecutionState示例

// Television recording is beginning. Enable away mode and prevent
// the sleep idle time-out.
SetThreadExecutionState(
    ES_CONTINUOUS | 
    ES_SYSTEM_REQUIRED | 
    ES_AWAYMODE_REQUIRED);

// Wait until recording is complete...
// Clear EXECUTION_STATE flags to disable away mode and allow the system
// to idle to sleep normally.
SetThreadExecutionState(ES_CONTINUOUS);
Run Code Online (Sandbox Code Playgroud)


Ric*_*key 10

您可以使用SetThreadExecutionState此处描述:

由于它是一个Win32 API函数,要从C#中使用它,你需要PInvoke它.这里描述了这些步骤,包括PreventSleep暂时禁用睡眠模式的示例方法:

  • 这在Windows 10(64位)上不起作用。 (2认同)