【问题标题】:How to check if there is no input from keyboard or mouse for a period of time in C#如何在C#中检查一段时间内键盘或鼠标是否没有输入
【发布时间】:2011-07-24 10:17:02
【问题描述】:

我正在尝试编写一行代码来检查是否在一分钟内没有来自键盘和鼠标的输入以及鼠标位置是否发生变化。如果此条件为真,则触发一个事件:

if ((no_Keyboard_input) && (no_mouse_input) && (no_change_in_mousePosition))
{
    start_timer;
    if (time_elapsed == 1 min)
    {
         playAnimation;
    }
}

【问题讨论】:

  • 你忘了说你的问题/问题是什么。
  • 你使用什么库? WinForms 还是 WPF?

标签: c#


【解决方案1】:

使用API​​,这是我之前使用的一个方法:

[DllImport("user32.dll")]
public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int GetTickCount();

[StructLayout(LayoutKind.Sequential)]
public struct LASTINPUTINFO
{
    public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));

    [MarshalAs(UnmanagedType.U4)]
    public int cbSize;

    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dwTime;
}

使用方法:

public static TimeSpan GetIdleTime()
{
    TimeSpan idleTime = TimeSpan.FromMilliseconds(0);

    LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
    lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
    lastInputInfo.dwTime = 0;

    if (GetLastInputInfo(ref lastInputInfo))
    {
        idleTime = TimeSpan.FromMilliseconds(GetTickCount() - (lastInputInfo.dwTime & uint.MaxValue));
        //idleTime = TimeSpan.FromSeconds(Convert.ToInt32(lastInputInfo.dwTime / 1000));
    }

    return idleTime;
}

编辑:添加GetTickCount() API 签名。

【讨论】:

  • +1(但我认为您忘记为GetTickCount() 添加 p/invoke 签名)。另外,我不确定将dwTime 截断为0xFFFFFFFF 是否是最好的主意(我宁愿做一个Int64 减法然后向下转换)。 (编辑) 好吧,实际上没有区别,因为dwTime 无论如何都是UInt32,没关系。
  • @Ismael:你试过这个吗?这能回答你的问题吗?
【解决方案2】:

我想看看Reactive Extensions 是否有类似的东西。它们提供了一种将许多不同事件组合成一个事件的好方法,以及完成它的好 LINQ 语法。

下面的代码未经测试,但您可以了解如何以这种方式完成它。

DateTime lastKeyboardInput, lastMouseInput;

var mouse = Observable.FromEvent<MouseEventArgs>(MouseDown);
var keyboard = Observable.FromEvent<KeyPressEventArgs>(KeyPress);
var seconds = Observable.Timer(TimeSpan.FromSeconds(1));
mouse.Subscribe(m => lastMouseInput = DateTime.Now());
keyboard.Subscribe(k => lastKeyboardInput = DateTime.Now());

var myEvent = from tick in seconds
          where lastKeyboardEvent < DateTime.Now() - TimeSpan.FromSeconds(60)
          where lastMouseEvent < DateTime.Now() - TimeSpawn.FromSeconds(60)
          select tick;

myEvent.Subscribe(t => playAnimation());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-26
    • 2011-12-09
    • 1970-01-01
    • 2011-07-20
    • 2011-06-01
    • 1970-01-01
    • 2015-12-13
    相关资源
    最近更新 更多