有时在应用中需要获取当前的系统状态,如果闲置一段时间将锁屏或自动登出。
代码示例
internal struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
[DllImport("User32.dll")]
public static extern bool LockWorkStation();
[DllImport("User32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO Dummy);
[DllImport("Kernel32.dll")]
private static extern uint GetLastError();
public static uint GetIdleTime()
{
LASTINPUTINFO LastUserAction = new LASTINPUTINFO();
LastUserAction.cbSize = (uint)Marshal.SizeOf(LastUserAction);
GetLastInputInfo(ref LastUserAction);
return ((uint)Environment.TickCount - LastUserAction.dwTime);
}
public static long GetTickCount()
{
return Environment.TickCount;
}
public static long GetLastInputTime()
{
LASTINPUTINFO LastUserAction = new LASTINPUTINFO();
LastUserAction.cbSize = (uint)Marshal.SizeOf(LastUserAction);
if (!GetLastInputInfo(ref LastUserAction))
{
throw new Exception(GetLastError().ToString());
}
return LastUserAction.dwTime;
}