using DM_Weight.Port; using DM_Weight.ViewModels; using log4net; using log4net.Core; using log4net.Repository.Hierarchy; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace DM_Weight.util { public class CheckComputerFreeState { private static readonly ILog logger = LogManager.GetLogger(typeof(CheckComputerFreeState)); /// /// 创建结构体用于返回捕获时间 /// [StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { /// /// 设置结构体块容量 /// [MarshalAs(UnmanagedType.U4)] public int cbSize; /// /// 抓获的时间 /// [MarshalAs(UnmanagedType.U4)] public uint dwTime; } [DllImport("user32.dll")] private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); /// /// 获取键盘和鼠标没有操作的时间 /// /// 用户上次使用系统到现在的时间间隔,单位为秒 public static long GetLastInputTime() { LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO(); vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo); if (!GetLastInputInfo(ref vLastInputInfo)) { return 0; } else { //var count = (Environment.TickCount & Int32.MaxValue) - (long)vLastInputInfo.dwTime; //var icount = count / 1000; //return icount; // 使用 64 位 TickCount 避免回绕问题 long currentTick = Environment.TickCount64; long lastInputTick = vLastInputInfo.dwTime; logger.Info($"获取用户未操作时间间隔{currentTick}-{lastInputTick}"); // 处理可能的回绕(虽然使用 64 位后极不可能发生) if (currentTick < lastInputTick) { // 发生了回绕,调整计算 lastInputTick -= uint.MaxValue + 1L; } long elapsedMilliseconds = currentTick - lastInputTick; long seconds = elapsedMilliseconds / 1000; logger.Info($"获取用户未操作时间间隔{currentTick}-{lastInputTick}-{elapsedMilliseconds}-{seconds}-{Math.Max(0, seconds)}"); return Math.Max(0, seconds); } } } }