如何进入空闲状态prevent的Windows? [英] How to prevent Windows from entering idle state?

查看:131
本文介绍了如何进入空闲状态prevent的Windows?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行在无任何Windows控件的背景C#应用程序。

I am working on a C# application which runs in the background without any Windows control.

我想从进入空闲状态通知Windows我的应用程序还活着,以prevent的Windows。

I want to notify Windows that my application is still alive to prevent Windows from going into the idle state.

有没有通知其Windows操作系统可以从我的应用程序调用的API的任何我的应用程序还活着?

Are there any APIs available to call from my application which notify the Windows OS that my application is still alive?

先谢谢了。

推荐答案

您已经使用的 SetThreadExecutionState 功能。事情是这样的:

You've to use SetThreadExecutionState function. Something like this:

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;
}

这篇关于如何进入空闲状态prevent的Windows?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆