Expressing the C # condition, "if the mouse / keyboard action has not occurred in the last" n "seconds,"

The question is how to check the C # program (running on Windows) to see if a key has been pressed or a mouse button has been pressed for a set amount of time in the past.

One of the solutions found uses the "KeyPress" event, but this only works if the control (or application) has focus. I am looking for a solution that works even while the program is running in the background.

In addition, it would be nice to have a way to exclude certain events (that is, the "Z" key) from the conditional.

+4
source share
1 answer

WinAPI has a function that does just that: GetLastInputInfo .

This feature is useful for detecting input idle. However, GetLastInputInfo does not provide system-wide user input in all sessions. Rather, GetLastInputInfo provides session input information only for the session that called the function.

And even an example on pinvoke.net . Here is my version:

public static TimeSpan GetIdleTime()
{
    var lastInputInfo = new LASTINPUTINFO
    {
        cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO))
    };

    if (!GetLastInputInfo(ref lastInputInfo))
        throw new Win32Exception("GetLastInputInfo failed");

    return TimeSpan.FromMilliseconds(Environment.TickCount - lastInputInfo.dwTime);
}

Relevant definitions for P / Invoke:

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

[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO
{
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 cbSize;

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

All Articles