移动鼠标以停止监视器睡眠

时间:2014-07-21 16:01:15

标签: c# winforms mouse

我想让我的显示器停止睡眠(由公司政策驱动)。以下是我正在使用的代码

while (true)
{
    this.Cursor = new Cursor(Cursor.Current.Handle);
    Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
    Cursor.Clip = new Rectangle(this.Location, this.Size);

    System.Threading.Thread.Sleep(2000);

    this.Cursor = new Cursor(Cursor.Current.Handle);
    Cursor.Position = new Point(Cursor.Position.X + 50, Cursor.Position.Y + 50);
    Cursor.Clip = new Rectangle(this.Location, this.Size);
}

我可以看到没有While循环的鼠标移动。但是,虽然它只移动鼠标一次然后限制鼠标移动到右侧。

有没有更好的方法呢?

2 个答案:

答案 0 :(得分:5)

如果您想保持计算机处于唤醒状态,请不要移动鼠标,只需告诉您的程序计算机必须保持清醒状态。移动鼠标是一种非常糟糕的做法。

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

然后,当您想要保持唤醒计算机时,只需致电ForceSystemAwake(),然后在完成后致电ResetSystemDefault()

答案 1 :(得分:1)

此方法每4分钟将鼠标移动1个像素,不会让您的显示器进入睡眠状态。

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