【C#】端末が操作されていない時間を取得する
Windows端末がどのくらいの間AFKであるかを知りたかったので調査結果をノートします。
参考サイト
csharp.hotexamples.com
【C#の場合】
internal struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } class Program { [System.Runtime.InteropServices.DllImport("User32.dll")] private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); static void Main(string[] args) { LASTINPUTINFO lastInputInfo = new LASTINPUTINFO(); lastInputInfo.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInputInfo); while (true) { Console.WriteLine(GetAfkSecond(lastInputInfo)); System.Threading.Thread.Sleep(1000); } } /// <summary> /// 端末が入力されていない時間を取得する /// </summary> /// <returns>AFK秒数</returns> public static long GetAfkSecond(LASTINPUTINFO lastInputInfo) { GetLastInputInfo(ref lastInputInfo); return ((Environment.TickCount - lastInputInfo.dwTime) / 1000); } }
【実行結果】