Detecting keyboard and mouse inactivity in C#

This Content Component encountered an error
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.
This was first published in October 2003

Dig deeper on Emerging SOA standards



Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.



Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: