-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNativeMethods.cs
48 lines (40 loc) · 1.37 KB
/
NativeMethods.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Runtime.InteropServices;
namespace Sandman;
public class NativeMethods
{
public static TimeSpan GetTimeSinceLastActivity()
{
LASTINPUTINFO lastInputInfo = LASTINPUTINFO.Create();
if (!GetLastInputInfo(ref lastInputInfo))
{
return TimeSpan.Zero;
}
// Even though it says "ticks," it's really milliseconds.
/// <see cref="https://docs.microsoft.com/en-us/dotnet/api/system.environment.tickcount"/>
uint msecEnvTicks = (uint)Environment.TickCount;
uint lastInputTick = lastInputInfo.dwTime;
uint idleTime = msecEnvTicks - lastInputTick;
return TimeSpan.FromMilliseconds(idleTime);
}
/// <see cref="https://www.pinvoke.net/default.aspx/Structures/LASTINPUTINFO.html"/>
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO
{
public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));
[MarshalAs(UnmanagedType.U4)]
public UInt32 cbSize;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTime; // Even though it says "ticks," it's really milliseconds.
public static LASTINPUTINFO Create() => new LASTINPUTINFO()
{
cbSize = (uint)SizeOf,
dwTime = 0,
};
}
/// <see cref="https://www.pinvoke.net/default.aspx/user32.GetLastInputInfo"/>
/// <param name="plii"></param>
/// <returns></returns>
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
}