脚本如何实现自动关屏

wen 实用脚本 2

本文目录导读:

脚本如何实现自动关屏

  1. Windows 系统(多种方式)
  2. Linux 系统
  3. macOS 系统
  4. 跨平台方案(Node.js)
  5. 综合方案 - 带条件的自动关屏
  6. 使用建议

我来介绍几种自动关屏的实现方法,根据使用场景选择适合的方案:

Windows 系统(多种方式)

PowerShell 脚本

# 立即关闭屏幕
Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class Monitor { [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); }'
$monitor = New-Object Monitor
[Monitor]::SendMessage([IntPtr]0xFFFF, 0x0112, [IntPtr]0xF170, [IntPtr]2)
# 定时关屏(60秒后)
Start-Sleep -Seconds 60
[Monitor]::SendMessage([IntPtr]0xFFFF, 0x0112, [IntPtr]0xF170, [IntPtr]2)

CMD 批处理

@echo off
:: 使用 nircmd 工具(需下载)
nircmd.exe monitor off
:: 或者使用 PowerShell 调用
powershell -command "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class M { [DllImport(\"user32.dll\")] public static extern int SendMessage(IntPtr h, int m, IntPtr w, IntPtr l); }'; [M]::SendMessage([IntPtr]0xFFFF, 0x0112, [IntPtr]0xF170, [IntPtr]2)"

Python 脚本

import ctypes
import time
def turn_off_monitor():
    """Windows下关闭显示器"""
    ctypes.windll.user32.SendMessageW(0xFFFF, 0x0112, 0xF170, 2)
def schedule_off(seconds):
    """定时关屏"""
    time.sleep(seconds)
    turn_off_monitor()
if __name__ == "__main__":
    # 5分钟后关屏
    schedule_off(300)

Linux 系统

Shell 脚本

#!/bin/bash
# 立即关闭屏幕(DPMS 方式)
xset dpms force off
# 10分钟后关闭
sleep 600 && xset dpms force off
# 或使用 vbetool(适合无电源管理的显示器)
vbetool dpms off

使用 systemd 定时器

创建定时任务文件 ~/.config/systemd/user/screen-off.service

[Unit]
Description=Turn off screen
[Service]
Type=oneshot
ExecStart=/usr/bin/xset dpms force off

macOS 系统

AppleScript

-- 立即关闭显示器
tell application "System Events"
    key code 144 -- 这是F2键(在某些Mac上可触发关屏)
end tell
-- 或使用 pmset 命令
do shell script "pmset displaysleepnow"

Shell 命令

# 立即睡眠显示器
pmset displaysleepnow
# 定时关闭(使用caffeinate避免系统睡眠)
sleep 300 && pmset displaysleepnow

跨平台方案(Node.js)

const { exec } = require('child_process');
function turnOffScreen() {
    const platform = process.platform;
    if (platform === 'win32') {
        exec('powershell -command "Add-Type -TypeDefinition \'using System; using System.Runtime.InteropServices; public class M { [DllImport(\"user32.dll\")] public static extern int SendMessage(IntPtr h, int m, IntPtr w, IntPtr l); }\'; [M]::SendMessage([IntPtr]0xFFFF, 0x0112, [IntPtr]0xF170, [IntPtr]2)"');
    } else if (platform === 'linux') {
        exec('xset dpms force off');
    } else if (platform === 'darwin') {
        exec('pmset displaysleepnow');
    }
}
// 定时执行
setTimeout(turnOffScreen, 5 * 60 * 1000); // 5分钟后

综合方案 - 带条件的自动关屏

import psutil
import ctypes
import time
import platform
class ScreenController:
    def __init__(self):
        self.system = platform.system()
    def is_idle(self, threshold_minutes=5):
        """检查系统是否空闲"""
        if self.system == "Windows":
            # 可以检查用户空闲时间(需要额外实现)
            return True
        elif self.system == "Linux":
            # 检查CPU使用率
            cpu_usage = psutil.cpu_percent(interval=1)
            return cpu_usage < 5
        return False
    def turn_off(self):
        """关闭屏幕"""
        if self.system == "Windows":
            ctypes.windll.user32.SendMessageW(0xFFFF, 0x0112, 0xF170, 2)
        elif self.system == "Linux":
            import subprocess
            subprocess.run(['xset', 'dpms', 'force', 'off'])
        elif self.system == "Darwin":
            import subprocess
            subprocess.run(['pmset', 'displaysleepnow'])
    def auto_off(self, check_interval=60, idle_threshold=300):
        """自动监控并关屏"""
        idle_seconds = 0
        while True:
            if self.is_idle():
                idle_seconds += check_interval
                if idle_seconds >= idle_threshold:
                    self.turn_off()
                    idle_seconds = 0
            else:
                idle_seconds = 0
            time.sleep(check_interval)
# 使用示例
controller = ScreenController()
controller.auto_off()

使用建议

  1. 简单场景:直接使用系统命令(如 xsetpmset
  2. 定时需求:使用 cron 或计划任务配合脚本
  3. 智能检测:结合 CPU 使用率、用户空闲时间等判断
  4. 远程控制:可以搭建 Web 服务,通过手机控制

如果需要更详细的某个平台的实现方案,或者有特定使用场景,请告诉我具体需求。

抱歉,评论功能暂时关闭!