问题
I want to stop my monitor to stop sleep (which is driven by company policies). Below is the code I am using for that
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);
}
I can see mouse moving without While loop. But with while it moves mouse only once and then it restrict the mouse to move to right side.
Is there any better way to do it?
回答1:
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
回答2:
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();
}
}
来源:https://stackoverflow.com/questions/24869508/moving-mouse-to-stop-monitor-from-sleeping