0

I have this problem today, i saw this solution:

How to detect my application is idle in c#?

I tried that, but my form is covered with userControls and other elements, and the mouseover or keydown events are only fired in the margins of those elements.

Is there a better way?

Community
  • 1
  • 1
Hahn86
  • 55
  • 1
  • 5
  • 17
  • 1
    Yes there is, can we show you? no we cant, why? because you havent shown us code that you have tried that we can improve on :) –  Jan 21 '13 at 16:18
  • Did you try looking at the [links in this answer](http://stackoverflow.com/a/5883435/479512) to your linked question. – Mark Hall Jan 21 '13 at 16:23

2 Answers2

2

Hacking together a solution with timers and mouse events is unnecessary. Just handle the Application.Idle event.

Application.Idle += Application_Idle;

private void Application_Idle(object sender, EventArgs e)
{
    //    The application is now idle.
}
JosephHirn
  • 720
  • 3
  • 9
1

If you want a more dynamic approach you could subscribe to all of the events in your Form because ultimately if a user is idle no events should ever be raised.

private void HookEvents()
{
    foreach (EventInfo e in GetType().GetEvents())
    {
        MethodInfo method = GetType().GetMethod("HandleEvent", BindingFlags.NonPublic | BindingFlags.Instance);
        Delegate provider = Delegate.CreateDelegate(e.EventHandlerType, this, method);
        e.AddEventHandler(this, provider);
    }
}

private void HandleEvent(object sender, EventArgs eventArgs)
{
    lastInteraction = DateTime.Now;
}

You could declare a global variable private DateTime lastInteraction = DateTime.Now; and assign to it from the event handler. You could then write a simple property to determine how many seconds have elapsed since the last user interaction.

private TimeSpan LastInteraction
{
    get { return DateTime.Now - lastInteraction; }
}

And then poll the property with a Timer as described in the original solution.

private void timer1_Tick(object sender, EventArgs e)
{
   if (LastInteraction.TotalSeconds > 90)
   {
       MessageBox.Show("Idle!", "Come Back! I need You!");
   }
}
Caster Troy
  • 2,796
  • 2
  • 25
  • 45