3

I am trying to write a line of code that checks if there is no input from keyboard and mouse and no change in the mouse position over a period of one minute. If this condition is true then trigger an event:

if ((no_Keyboard_input) && (no_mouse_input) && (no_change_in_mousePosition))
{
    start_timer;
    if (time_elapsed == 1 min)
    {
         playAnimation;
    }
}
vgru
  • 49,838
  • 16
  • 120
  • 201
Ismael
  • 343
  • 1
  • 4
  • 7

2 Answers2

9

Using API, Here is a method I used before:

[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;
}

How to use it:

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;
}

Edit: Add GetTickCount() API Signature.

Jalal Said
  • 15,906
  • 7
  • 45
  • 68
  • +1 (but I think you forgot to add the p/invoke signature for `GetTickCount()`). Also, I am not sure if truncating `dwTime` to `0xFFFFFFFF` is the best idea (I would rather do an `Int64` subtraction and then downcast). **(Edit)** Ok, actually there is no difference since `dwTime` is `UInt32` anyway, never mind. – vgru Jul 24 '11 at 10:32
  • @Ismael: did you try this? does this answers your question? – Jalal Said Jul 27 '11 at 15:20
0

I'd have a look at Reactive Extensions for something like this. They provide a nice way of composing many different events into a single one, and the nice LINQ syntax to get it done.

The code below is untested, but an idea of how you might get it done this way.

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());
Mark H
  • 13,797
  • 4
  • 31
  • 45