如何检测我的应用程序在c#中处于空闲状态(包含表单)?

如何检测我的应用程序在c#中处于空闲状态(包含表单)?,c#,detect,C#,Detect,我今天遇到了这个问题,我看到了这个解决方案: 我试过了,但是我的表单被userControls和其他元素覆盖,mouseover或keydown事件只在这些元素的边距处触发 有更好的方法吗?不需要用计时器和鼠标事件来拼凑解决方案。只需处理Application.Idle事件 Application.Idle += Application_Idle; private void Application_Idle(object sender, EventArgs e) { // Th

我今天遇到了这个问题,我看到了这个解决方案:

我试过了,但是我的表单被userControls和其他元素覆盖,mouseover或keydown事件只在这些元素的边距处触发


有更好的方法吗?

不需要用计时器和鼠标事件来拼凑解决方案。只需处理Application.Idle事件

Application.Idle += Application_Idle;

private void Application_Idle(object sender, EventArgs e)
{
    //    The application is now idle.
}

用计时器和鼠标事件将解决方案拼凑在一起是不必要的。只需处理Application.Idle事件

Application.Idle += Application_Idle;

private void Application_Idle(object sender, EventArgs e)
{
    //    The application is now idle.
}

如果您想要更动态的方法,您可以订阅
表单中的所有事件,因为最终如果用户空闲,则不应引发任何事件

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;
}
您可以声明一个全局变量
private DateTime lastInteraction=DateTime.Now并从事件处理程序分配给它。然后,您可以编写一个简单的属性来确定自上次用户交互以来经过了多少秒

private TimeSpan LastInteraction
{
    get { return DateTime.Now - lastInteraction; }
}
然后使用
计时器轮询属性,如原始解决方案中所述

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

如果您想要更动态的方法,您可以订阅
表单中的所有事件,因为最终如果用户空闲,则不应引发任何事件

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;
}
您可以声明一个全局变量
private DateTime lastInteraction=DateTime.Now并从事件处理程序分配给它。然后,您可以编写一个简单的属性来确定自上次用户交互以来经过了多少秒

private TimeSpan LastInteraction
{
    get { return DateTime.Now - lastInteraction; }
}
然后使用
计时器轮询属性,如原始解决方案中所述

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

有,我们可以给你看看吗?不,我们不能,为什么?因为您没有向我们展示您尝试过的代码,我们可以对其进行改进:)您是否尝试查看链接问题的链接。是的,我们可以展示给您吗?不,我们不能,为什么?因为您没有向我们展示您尝试过的代码,我们可以对其进行改进:)您是否尝试查看链接问题的答案。但是,您必须将一些内容拼凑在一起,以显示用户没有空闲:D但是您必须将一些内容拼凑在一起,以显示用户没有空闲:D