2014-07-21 77 views
0

我想停止监视器停止睡眠(这是由公司策略驱动的)。以下是我正在使用的代码移动鼠标以停止睡眠监视器

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循环的鼠标移动。但是,虽然它只移动鼠标一次,然后限制鼠标移动到右侧。

有没有更好的方法来做到这一点?

+1

http://www.perlmonks.org/?node=xy+problem – EZI

+0

添加一个'Thread.Sleep(2000);'最后,你会看到这个举动。但我不知道这是否会阻止显示器进入睡眠状态。 – Bolu

+0

显示器已被您的公司策略设置为睡眠状态的原因有很多,打破这些策略听起来像是baaaaad的想法。 – DavidG

回答

3

如果你想让你的电脑保持清醒,不要移动鼠标,只要告诉你的程序,电脑必须保持清醒。移动鼠标是一个非常糟糕的做法。

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()当你完成

+0

这可能适用于屏幕保护程序,但不适用于PowerSaver选项中的显示器睡眠。 –

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