我创建了一个小型 C# 控制台应用程序来在屏幕上移动指针,希望这可以防止屏幕在几分钟后休眠/锁定。不幸的是,几分钟后屏幕仍然进入休眠状态。
有谁知道是否真的可以用 C# 编写一些类似于用户输入(鼠标或键盘)的东西,并防止屏幕自动休眠/锁定?
这是我所拥有的,我认为它可能会起作用。
class Program
{
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
static Random rnd = new Random();
static void Main(string[] args)
{
Rectangle screenRes = Screen.PrimaryScreen.Bounds;
int widtMax = screenRes.Width;
int heighMax = screenRes.Height;
int w;
int h;
do
{
while (!Console.KeyAvailable)
{
w = rnd.Next(1, widtMax);
h = rnd.Next(1, heighMax);
SetCursorPos(w, h);
System.Threading.Thread.Sleep(1000);
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
}
最佳答案
您可以使用 SetThreadExecutionState
Enables an application to inform the system that it is in use, thereby preventing the system from entering sleep or turning off the display while the application is running.
备注
Calling
SetThreadExecutionState
withoutES_CONTINUOUS
simply resets the idle timer; to keep the display or system in the working state, the thread must callSetThreadExecutionState
periodically.To run properly on a power-managed computer, applications such as fax servers, answering machines, backup agents, and network management applications must use both
ES_SYSTEM_REQUIRED
andES_CONTINUOUS
when they process events. Multimedia applications, such as video players and presentation applications, must useES_DISPLAY_REQUIRED
when they display video for long periods of time without user input. Applications such as word processors, spreadsheets, browsers, and games do not need to callSetThreadExecutionState
.
DllImport
[DllImport("kernel32.dll", CharSet = CharSet.Auto,SetLastError = true)]
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
}
用法
void PreventSleep ()
{
// Prevent Idle-to-Sleep (monitor not affected) (see note above)
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_AWAYMODE_REQUIRED);
}
2021 年 2 月 8 日更新:
如果有人正在寻找一个完整的例子,这是我在 github 上找到的一个实现了这个的项目:https://github.com/pedrolcl/screensaver-disabler
关于c# - 使用 C# 防止屏幕休眠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49045701/