问题
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?
回答1:
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.
}
回答2:
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!");
}
}
来源:https://stackoverflow.com/questions/14442713/how-to-detect-my-application-is-idle-in-c-sharp-form-covered