[PowerShell]一段时间无操作后自动锁屏
# 设置自动锁屏时间(秒)
$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 秒"
}
}
}

墨笑
如果我的文章能帮到你,还请不吝打赏,五块三块不嫌多,一块五毛不嫌少
版权属于:
墨笑的精神小憩之地 的博客
本文链接:
https://www.whisperdiary.cn/index.php/archives/81/
作品采用:
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可
推荐阅读
评论已关闭