Console App to Report the Inactivity of a User

Publish date: May 1, 2019
Tags: .net, c#, windows, console

Ethical side

I remember on day seeing a requirement on a local freelance site, which said that the client wanted a windows application which will monitor his employees and notify him, if they didn’t move their mouse or touched a keyboard within the last 10 minutes.

I thought to myself: “Wow, do micro managers like this still exist?” I would recommend this person to at least try to find another way of making sure his employees do what they are paid for (if that was an option in this scenario).

Technical side

Whether you consider this ethical or not, it is an interesting technical problem, which has a solution. Here is where you want to start, when creating this kind of solution:

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace ActivityReporter
{
   class Program
   {
       static void Main(string[] args)
       {
           monitorDistanceBetweenInputs();
       }

       [DllImport("User32.dll")]
       private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

       [StructLayout(LayoutKind.Sequential)]
       internal struct LASTINPUTINFO
       {
           public uint cbSize;
           public uint dwTime;
       }

       private static void monitorDistanceBetweenInputs()
       {
           while (true)
           {
               Thread.Sleep(1000);
               var lastInputInfo = new LASTINPUTINFO();
               lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
               GetLastInputInfo(ref lastInputInfo);
               var lastInput = DateTime.Now.AddMilliseconds(
                   -(Environment.TickCount - lastInputInfo.dwTime));
               if ((DateTime.Now - lastInput).Seconds > 10)
               {
                   //this is where you would send the notification to the manager
                   Console.WriteLine("Idle for too long");
               }
               Console.WriteLine(lastInputInfo.dwTime);
           }
       }
   }
}

This will not work cross-platform on .NET Core (yet?), just on Windows, as it uses DLLImport of User32.dll, which you will not find on Mac on Linux. So thats it, happy coding!