如何在C#中检查键盘或鼠标输入是否有一段时间没有

Ism*_*ael 3 c#

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

if ((no_Keyboard_input) && (no_mouse_input) && (no_change_in_mousePosition))
{
    start_timer;
    if (time_elapsed == 1 min)
    {
         playAnimation;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jal*_*aid 9

使用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;
}
Run Code Online (Sandbox Code Playgroud)

如何使用它:

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;
}
Run Code Online (Sandbox Code Playgroud)

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