Reputation: 203
I would like to simulate a user input to prevent the screen from locking.
public Form1()
{
aTimer = new System.Threading.Timer(OnTimedEvent, null, 5000, Timeout.Infinite);
}
private void OnTimedEvent(Object source)
{
Stopwatch watch = new Stopwatch();
watch.Start();
if (IdleTimeFinder.GetIdleTime() > 2000)
{
SendKeys.SendWait({CAPSLOCK});
}
aTimer.Change(Math.Max(0, 5000 - watch.ElapsedMilliseconds), Timeout.Infinite);
}
My problem is that sometimes capslock stays on or off other times it blinks. It's not very predicable.
Upvotes: 1
Views: 413
Reputation: 2339
I think you may have a race condition between multiple threads giving you inconsistent results.
The correct way to prevent the computer from sleeping is to use the SetThreadExecutionState function.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa373208%28v=vs.85%29.aspx
You can p/Invoke this one pretty easily, I have used it from C# in the past.
To call it from C# you will want to use the following declarations:
http://www.pinvoke.net/default.aspx/kernel32.setthreadexecutionstate
[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
}
Upvotes: 3