Moving mouse to stop monitor from sleeping [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-06 11:16:56

If you want to keep your computer awake, dont move the mouse, just tell your program that computer must keep awake. Moving the mouse is a very bad practice.

public class PowerHelper
{
    public static void ForceSystemAwake()
    {
        NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_CONTINUOUS |
                                              NativeMethods.EXECUTION_STATE.ES_DISPLAY_REQUIRED |
                                              NativeMethods.EXECUTION_STATE.ES_SYSTEM_REQUIRED |
                                              NativeMethods.EXECUTION_STATE.ES_AWAYMODE_REQUIRED);
    }

    public static void ResetSystemDefault()
    {
        NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_CONTINUOUS);
    }
}

internal static partial class NativeMethods
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);

    [FlagsAttribute]
    public enum EXECUTION_STATE : uint
    {
        ES_AWAYMODE_REQUIRED = 0x00000040,
        ES_CONTINUOUS = 0x80000000,
        ES_DISPLAY_REQUIRED = 0x00000002,
        ES_SYSTEM_REQUIRED = 0x00000001

        // Legacy flag, should not be used.
        // ES_USER_PRESENT = 0x00000004
    }
}

and then, just call ForceSystemAwake() when you want to keep awake your computer, then call ResetSystemDefault() when you have finish

This method moves the mouse by 1 pixel every 4 minutes and it will not let your monitor to sleep.

using System;
using System.Drawing;
using System.Windows.Forms;

static class Program
{
    static void Main()
    {
        Timer timer = new Timer();
        // timer.Interval = 4 minutes
        timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 /TimeSpan.TicksPerMillisecond);
        timer.Tick += (sender, args) => { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); };
        timer.Start();
        Application.Run();
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!