ユーザーがマウスやキーボードなどの操作をしていない状態の時間を取得するGetLastInputInfo APIを使ったサンプルコードになります。
サンプルコードは C#, Visual Basic(VB)になります。
ユーザーがコンピュータを操作していない状態を取得したい場合は、GetLastInputInfo APIで状態を取得できます。
本サンプルコードは、無操作状態の監視のみになるので、実際に無操作時間をカウントする部分のプログラミングは別途必要になります。
以下のサンプルコードを実行すると、以下のような動作になります。
キーボードやマウスを触る(操作する)と終了するだけです。
using System; 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) { Console.WriteLine("Start : GetLastInputInfo API sample"); LASTINPUTINFO lastInPut = new LASTINPUTINFO(); lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut); uint operation_time = 0; bool operation = false; while (!operation) { try { if (!GetLastInputInfo(ref lastInPut)) { throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } if (operation_time == 0) { operation_time = lastInPut.dwTime; } if (operation_time != lastInPut.dwTime) { operation = true; } } catch (Exception ex) { Console.WriteLine("Exception:{0}", ex.Message); } System.Threading.Thread.Sleep(100); } Console.WriteLine("Stop: ** You touched the computer.(^^)/ **"); } }
Module Module1 Friend Structure LASTINPUTINFO Public cbSize As UInteger Public dwTime As UInteger End Structure <Runtime.InteropServices.DllImport("User32.dll")> Private Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean End Function Sub Main() Console.WriteLine("Start : GetLastInputInfo API sample") Dim lastInPut As LASTINPUTINFO = New LASTINPUTINFO() lastInPut.cbSize = CUInt(System.Runtime.InteropServices.Marshal.SizeOf(lastInPut)) Dim operation_time As UInteger = 0 Dim operation As Boolean = False While Not operation Try If Not GetLastInputInfo(lastInPut) Then Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) End If If operation_time = 0 Then operation_time = lastInPut.dwTime End If If operation_time <> lastInPut.dwTime Then operation = True End If Catch ex As Exception Console.WriteLine("Exception:{0}", ex.Message) End Try Threading.Thread.Sleep(100) End While Console.WriteLine("Stop: ** You touched the computer.(^^)/ **") End Sub End Module
以上、ユーザーがコンピュータを操作していない状態を取得するサンプルコードでした。