Ask the Expert

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#.

    Requires Free Membership to View

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

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: