问题
I have created a small C# console app to move the pointer around the screen, in the hope that this would prevent the screen from sleeping / locking after a few minutes. Unfortunately the screen still goes to sleep after a few minutes.
Does anyone know if it's actually possible to write something in C# which will act like user input (either mouse or keyboard), and prevent the screen from sleeping / locking automatically?
Here is what I have, which I thought might do the trick.
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);
}
}
回答1:
You can make use of 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.
Remarks
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);
Enums
[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
}
Usage
void PreventSleep ()
{
// Prevent Idle-to-Sleep (monitor not affected) (see note above)
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_AWAYMODE_REQUIRED);
}
.
来源:https://stackoverflow.com/questions/49045701/prevent-screen-from-sleeping-with-c-sharp