Detecting user idleness

Another Win32 thing that didn’t make it into the framework… sometimes you need to know if the user is idle.  Win32 provides a handy function for this, GetLastInputInfo.  Here’s the stuff you need to call it from C#:


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


[DllImport(“USER32.DLL”, SetLastError=true)]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO ii);


int GetIdleTime()
{
  LASTINPUTINFO ii = new
LASTINPUTINFO();
  ii.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(ii);
 
if (GetLastInputInfo(ref
ii))
  {
   
// Got it, return the delta
   
return
Environment.TickCount – ii.dwTime;
  } else
  {
    // Fill in your own blank here
  }
}


Caveat:  GetLastInputInfo doesn’t work on the Win9x OS’s, and there doesn’t seem to be any way of using the other mechanism commonly used for detecting user idleness, installing a global keyboard and mouse hook via SetWindowsHookEx, from C#.  Doh.