Created
November 29, 2019 18:42
-
-
Save Paskowsky/d59930f4e4195dd93d6fb6ee6344861d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Linq; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
using System.Threading; | |
class UserActivityMonitor | |
{ | |
public event EventHandler OnIdleEnter; | |
public event EventHandler OnIdleExit; | |
public int IdleTimeSeconds { get; set; } | |
public bool IsRunning { get; private set; } | |
public UserActivityMonitor(int idleTime) | |
{ | |
this.IdleTimeSeconds = idleTime; | |
} | |
private bool inIdle; | |
private Thread monitorThread; | |
private void WorkerThread() | |
{ | |
LASTINPUTINFO plii = new LASTINPUTINFO(); | |
plii.cbSize = (uint)Marshal.SizeOf(plii); | |
while (IsRunning) | |
{ | |
if (!NativeMethods.GetLastInputInfo(ref plii)) | |
{ | |
throw new Win32Exception(); | |
} | |
TimeSpan lastInputTime = TimeSpan.FromMilliseconds((((Environment.TickCount & int.MaxValue) - (plii.dwTime & int.MaxValue)) & int.MaxValue)); | |
if (lastInputTime.TotalSeconds > IdleTimeSeconds) | |
{ | |
if (!inIdle) | |
{ | |
inIdle = true; | |
OnIdleEnter?.Invoke(this, null); | |
} | |
Thread.Sleep(IdleTimeSeconds * 125); | |
} | |
else | |
{ | |
if (inIdle) | |
{ | |
inIdle = false; | |
OnIdleExit?.Invoke(this, null); | |
} | |
Thread.Sleep(IdleTimeSeconds * 500); | |
} | |
} | |
} | |
private Thread StartWorkerThread() | |
{ | |
inIdle = true; | |
Thread t = new Thread(new ThreadStart(WorkerThread)); | |
t.Start(); | |
return t; | |
} | |
public void Start() | |
{ | |
if (IsRunning) | |
return; | |
if (monitorThread != null) | |
{ | |
if (monitorThread.IsAlive) | |
return; | |
monitorThread = null; | |
} | |
IsRunning = true; | |
monitorThread = StartWorkerThread(); | |
} | |
public void Stop() | |
{ | |
if (!IsRunning) | |
return; | |
if (monitorThread == null) | |
return; | |
if (!monitorThread.IsAlive) | |
return; | |
IsRunning = false; | |
monitorThread.Join(); | |
monitorThread = null; | |
} | |
} | |
static class NativeMethods | |
{ | |
[DllImport("user32")] | |
internal static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); | |
} | |
struct LASTINPUTINFO | |
{ | |
public uint cbSize; | |
public uint dwTime; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment