Problem solve Get help with specific problems with your technologies, process and projects.

Detecting keyboard and mouse inactivity in C

I would like to know how to detect the keyboard and mouse inactivity (meaning no response from the user for a period...

of time) in C#. Well, there is no automatic way to "detect" inactivity. However, events are raised whenever the user types on the keyboard or moves the mouse. What you could do is: 1. Place a timer on the form 2. Create a local DateTime field (Let's call it _LastActivityTime) that will hold the DateTime of last mouse or keyboard activity. 3. Update _LastActivityTime to DateTime.Now in KeyPress and MouseMove events. 4. In the Tick event of the time object, compare the value of _LastActivityTime to DateTime.Now something like this:

   private void timer1_Tick(object sender, System.EventArgs e)
         if (_LastActivityTime.AddSeconds(5) < DateTime.Now)
            // Do something because timeout has been reached.
            // Note that this will fire with every timer interval!

I've added an interval of 5 seconds to the _LastActivityTime. You would add whatever your maximum inactivity period would be.

A bit inelegant, perhaps, but it should work.

Dig Deeper on Topics Archive