Q

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.
This was last published in October 2003

Dig Deeper on Emerging SOA standards

PRO+

Content

Find more PRO+ content and other member only offers, here.

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.

Start the conversation

Send me notifications when other members comment.

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

Please create a username to comment.

-ADS BY GOOGLE

SearchSoftwareQuality

SearchCloudApplications

SearchAWS

TheServerSide

SearchWinDevelopment

Close