const { exec } = require('child_process'); const CHECK_INTERVAL = 30 * 1000; // 每 30 秒检查一次 const IDLE_LIMIT = 60 * 1000; // 空闲超过 60 秒则触发 // 封装执行 PowerShell 的方法(使用 UTF-16LE 编码避免引号转义问题) function runPs(script) { return new Promise((resolve, reject) => { const encoded = Buffer.from(script, 'utf16le').toString('base64'); exec(`powershell -NoProfile -EncodedCommand "${encoded}"`, (err, stdout) => { if (err) reject(err); else resolve(stdout.trim()); }); }); } // 获取当前系统空闲毫秒数 async function getIdleTime() { const ps = ` Add-Type @" using System; using System.Runtime.InteropServices; public class IdleChecker { [DllImport("user32.dll")] public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); public struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } public static uint GetIdleMilliseconds() { LASTINPUTINFO lii = new LASTINPUTINFO(); lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO)); GetLastInputInfo(ref lii); return (uint)Environment.TickCount - lii.dwTime; } } "@ [IdleChecker]::GetIdleMilliseconds() `; const result = await runPs(ps); return parseInt(result, 10); } // 模拟按下 F15 键(无任何副作用) async function pressF15() { const ps = ` $wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys('{F15}'); `; await runPs(ps); } console.log('✅ 防锁屏脚本已启动 (PowerShell 模式)'); console.log(`⏱️ 检测到空闲 ${IDLE_LIMIT/1000} 秒后,自动模拟按键防止锁屏。`); setInterval(async () => { try { const idleMs = await getIdleTime(); if (idleMs > IDLE_LIMIT) { console.log(`🔄 已空闲 ${Math.round(idleMs/1000)} 秒,模拟 F15 重置计时器...`); await pressF15(); } } catch (e) { console.error('⚠️ 执行出错:', e.message); } }, CHECK_INTERVAL); // 按 Ctrl+C 退出时提示 process.on('SIGINT', () => { console.log('\n🛑 脚本已停止'); process.exit(0); });