C# 记录一个获取系统空闲时间的函数,可用于判断休眠
核心代码是调用 Windows API GetLastInputInfo() :
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public static uint GetIdleTime()
{
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
if (GetLastInputInfo(ref lastInputInfo))
{
uint idleTime = (uint)Environment.TickCount - lastInputInfo.dwTime;
return idleTime / 1000; // Convert milliseco