I am working on an Windows Form that will run to Lock the Desktop after x minutes
of User's inactivity.
I tried GetLastInputInfo()
but it only detect the User's inactivity based on Keyboard and Mouse movement only. Well, it is written on their explanation (or do I misunderstand it?).
This function is useful for input idle detection. However, GetLastInputInfo does not provide system-wide user input information across all running sessions. Rather, GetLastInputInfo provides session-specific user input information for only the session that invoked the function.
*Now I understand the definition of system-wide user input, thanks to @Garr Godfrey
And now, I want to extend the functionality by detecting a running media player (From web browser or Window's media player).
For example:
- User "A" did nothing in his/her Desktop, so the Timer start
- But if he/she watch a youtube video or a video through the Windows's media player, The timer is restarted to 0 again until the player stop playing any media.
My current Code is like this
public class Form1 : Form
{
private struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public CancellationTokenSource ctsCheckInactive;
public int InactivityCheckTimeGap = 1 * 1000;
public int InactiveThresholdInS = 15 * 60 *1000; //15 minute
public Form1()
{
InitializeComponent();
CheckInactivity();
}
public void CheckInactivity()
{
ctsCheckInactive = new CancellationTokenSource();
var t = System.Threading.Tasks.Task.Run(async () => await CheckInactivityRoutine(ctsCheckInactive.Token), ctsCheckInactive.Token);
}
private async Task CheckInactivityRoutine(CancellationToken ct)
{
while (true)
{
var time = GetLastInputTime();
//Here I want to add Media Player Detection
//if(DetectMediaPlayer() == true){
// time = 0
//}
//For debugging
Console.WriteLine(time + " Sec");
If(time > InactiveThresholdInS){
//Lock the PC or show screen saver
}
ct.ThrowIfCancellationRequested();
await System.Threading.Tasks.Task.Delay(InactivityCheckTimeGap);
}
}
static uint GetLastInputTime()
{
uint idleTime = 0;
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
lastInputInfo.dwTime = 0;
//Gets the number of milliseconds elapsed since the system started.
uint envTicks = (uint)Environment.TickCount;
if (GetLastInputInfo(ref lastInputInfo))
{
uint lastInputTick = lastInputInfo.dwTime;
idleTime = envTicks - lastInputTick;
}
return ((idleTime > 0) ? (idleTime / 1000) : 0);
}
}
Does anyone know how to achieve that?
My program is minimized to windows tray and always running after the user logged in. And it has the ability like this.
EDIT: Added pseudo code