Windows には、ユーザーの対話性やその他のタスク (誰かがビデオを見ているなど) をチェックして、スクリーンセーバーを表示する (または画面をオフにする) タイミングを決定する内部メカニズムがあります。
ユーザーがアクティブかどうか、または最後にアクティブだったのはいつかを確認できる Win API はありますか?
Windows には、ユーザーの対話性やその他のタスク (誰かがビデオを見ているなど) をチェックして、スクリーンセーバーを表示する (または画面をオフにする) タイミングを決定する内部メカニズムがあります。
ユーザーがアクティブかどうか、または最後にアクティブだったのはいつかを確認できる Win API はありますか?
これを「アイドルタイマー」と呼びます。SystemPowerInformation を要求してCallNtPowerInformation()をピンボークすることで、その値を取得できます。返された SYSTEM_POWER_INFORMATION.TimeRemaining フィールドは、アイドル タイマーの残り時間を示します。SystemExecutionState リクエストは、ビデオを表示するアプリで行われるように、スレッドが SetThreadExecutionState() を呼び出してタイマーを停止したかどうかを示します。
using System;
using System.Runtime.InteropServices;
public static class PowerInfo {
public static int GetIdleTimeRemaining() {
var info = new SYSTEM_POWER_INFORMATION();
int ret = GetSystemPowerInformation(SystemPowerInformation, IntPtr.Zero, 0, out info, Marshal.SizeOf(info));
if (ret != 0) throw new System.ComponentModel.Win32Exception(ret);
return info.TimeRemaining;
}
public static int GetExecutionState() {
int state = 0;
int ret = GetSystemExecutionState(SystemExecutionState, IntPtr.Zero, 0, out state, 4);
if (ret != 0) throw new System.ComponentModel.Win32Exception(ret);
return state;
}
private struct SYSTEM_POWER_INFORMATION {
public int MaxIdlenessAllowed;
public int Idleness;
public int TimeRemaining;
public byte CoolingMode;
}
private const int SystemPowerInformation = 12;
private const int SystemExecutionState = 16;
[DllImport("powrprof.dll", EntryPoint = "CallNtPowerInformation", CharSet = CharSet.Auto)]
private static extern int GetSystemPowerInformation(int level, IntPtr inpbuf, int inpbuflen, out SYSTEM_POWER_INFORMATION info, int outbuflen);
[DllImport("powrprof.dll", EntryPoint = "CallNtPowerInformation", CharSet = CharSet.Auto)]
private static extern int GetSystemExecutionState(int level, IntPtr inpbuf, int inpbuflen, out int state, int outbuflen);
}
GetLastInputInfo関数を確認する必要があります。この関数は、最後のユーザー入力からのティック カウントを含む構造体を返します。1 ティックは 1 ミリ秒です。次に、これをEnvironment.TickCountによって返される値と比較して、最後のユーザー入力からの経過時間をミリ秒単位で取得できます。
この関数の AP/Invoke 定義は、http ://www.pinvoke.net/default.aspx/user32.GetLastInputInfo から入手できます。
ただし、によって返されるティック値GetLastInputInfo
は 50 日足らずでゼロに戻りますがEnvironment.TickCount
、25 日足らずでラップするGetLastInputInfo
ことに注意してください。ほとんどの場合、これはおそらく大きな問題にはなりませんが、月に 1 回程度、時折奇妙な動作が発生する可能性があることに注意してください。