detect system wide user idle time

Answered detect system wide user idle time

  • Wednesday, May 23, 2007 11:26 AM
     
     
    How can I get the time a user has been idle (i.e didn't perform any input) system wide?  Similar like the screensaver or Windows Live Messenger does it.  Even better would be to get notified via an event when the idle time has exceeded a specific timespan. Maybe there is something for that in WMI ?

All Replies

  • Wednesday, May 23, 2007 12:38 PM
    Moderator
     
     Answered
    You can P/Invoke the GetLastInputInfo() API function.  Check this thread for code to detect the screen saver turning on.  Here's a sample app that demonstrates the API function:

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;

    namespace WindowsApplication1 {
      public partial class Form1 : Form {
        public Form1() {
          InitializeComponent();
          timer1.Interval = 1000;
          timer1.Tick += CheckLastInput;
          timer1.Enabled = true;
        }
        private void CheckLastInput(object sender, EventArgs e) {
          LastInputInfo info = new LastInputInfo();
          info.cbSize = Marshal.SizeOf(info);
          GetLastInputInfo(ref info);
          uint tick = GetTickCount();
          uint msec = tick - info.dwTime;
          Console.WriteLine("Last input was {0} milliseconds ago", msec);
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct LastInputInfo {
          public int cbSize;
          public uint dwTime;
        }
        [DllImport("user32.dll")]
        private static extern bool GetLastInputInfo(ref LastInputInfo info);
        [DllImport("kernel32.dll")]
        private static extern uint GetTickCount();
      }
    }
  • Wednesday, July 01, 2009 6:15 AM
     
     
    Thanks a Lot,

    Saved a lot of time.
  • Wednesday, October 07, 2009 9:47 PM
     
     
    I'd like to know how Screensavers do it because this isn't it. Close but no cigar (for my problem).