# 设置自动锁屏时间(秒)
$LOCK_TIME = 300
$time_remaining = $LOCK_TIME

# 导入必要的 Windows API
Add-Type @"
using System;
using System.Runtime.InteropServices;

public class UserActivity
{
    [DllImport("user32.dll")]
    public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

   [StructLayout(LayoutKind.Sequential)]
   public struct LASTINPUTINFO
   {
       public int cbSize;
       public uint dwTime;
   }

   public static uint GetIdleTime()
   {
       LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
       lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
       GetLastInputInfo(ref lastInputInfo);
       return ((uint)Environment.TickCount - lastInputInfo.dwTime) / 1000; // return idle time in seconds
   }
   }

   "@
   # 锁屏函数
   function Lock-Screen {
       rundll32.exe user32.dll,LockWorkStation
   }

   # 主监测循环
   while ($true) {
       Start-Sleep -Seconds 1 # 每秒检查一次
       $idleTime = [UserActivity]::GetIdleTime()
   
       if ($idleTime -ge $LOCK_TIME) {
           Write-Host "没有操作,将自动锁屏..."
           Lock-Screen
           $time_remaining = $LOCK_TIME  # 重置时间
       } else {
           $remainingTime = $LOCK_TIME - $idleTime
           if ($idleTime -lt $LOCK_TIME) {
               Write-Host "距离自动锁屏还有: $remainingTime 秒"
           }
       }
   }