我想停止显示器以停止睡眠(这是由公司政策驱动的)。以下是我为此使用的代码
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);
}
Run Code Online (Sandbox Code Playgroud)
我可以看到没有While循环的鼠标移动。但是当它只移动鼠标一次,然后限制鼠标向右移动时。
有什么更好的方法吗?
如果要使计算机保持睡眠状态,请不要移动鼠标,只需告诉程序计算机必须保持睡眠状态即可。移动鼠标是非常糟糕的做法。
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
}
}
Run Code Online (Sandbox Code Playgroud)
然后,只要ForceSystemAwake()您想保持计算机唤醒就打电话,然后ResetSystemDefault()在结束时打电话给