python实现防止windows自动锁屏

起因

因为公司内部用软件限制了锁屏时间,调整注册表、修改组策略、修改屏保啥的都试了,电脑该锁屏还是锁屏,经常在堡垒机执行一个长一点的命令的时候,上个厕所功夫回来就锁屏了,再解锁,堡垒机就断开连接了。严重打扰工作效率,所以使用python定时向windows的API发送请求来防止锁屏。

优点

相比使用鼠标定时连点、或者触发键盘按键的方式,此方法不影响任何操作。

功能

  1. 默认200秒执行一次,可以根据自己的锁屏时间调整,比锁屏时间提前一些就行。
  2. 有开始和停止按钮
  3. 点击开始或右上角叉号后会自动最小化到托盘,不占用开始任务拦,退出时直接在托盘点右键-退出即可。

参考

向windows发送API参考了下面链接中“hrpzcf”的回复。
https://fishc.com.cn/thread-213259-1-1.html

完整代码

python版本:3.11
第三方包:PyQt5、pyInstaller

import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QLabel, QLineEdit,
                             QSystemTrayIcon, QAction, QMenu)
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt, QTimer
from ctypes import windll, c_uint
 
 
class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
 
        self.KERNEL = windll.kernel32
        self.KERNEL.SetThreadExecutionState.restype = c_uint
        self.KERNEL.SetThreadExecutionState.argtypes = (c_uint,)
        self.RESTORE = 0x80000000
        self.PREVENT = 0x00000001 | 0x00000002 | 0x80000000
 
        self.sleepTime = 200  # 默认为200秒
        self.isRunning = False
 
        self.initUI()
 
    def initUI(self):
        self.setWindowTitle("noLockScreen")  # 设置窗口标题
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.Tool)  # 设置窗口标志
 
        self.setGeometry(0, 0, 300, 150)
        self.centerOnScreen()
 
        self.label = QLabel('睡眠时间(秒):', self)
        self.label.setGeometry(30, 20, 150, 20)
 
        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(160, 20, 100, 20)
        self.lineEdit.setText(str(self.sleepTime))  # 设置默认值为200秒
 
        self.button = QPushButton('开始', self)
        self.button.setGeometry(30, 80, 100, 40)
        self.button.clicked.connect(self.onButtonClick)
 
        self.tray_icon = QSystemTrayIcon(self)
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icon.png')
        self.tray_icon.setIcon(QIcon(icon_path))
 
        # 设置系统托盘图标的菜单
        self.tray_menu = QMenu(self)
        self.restore_action = QAction("恢复", self)
        self.restore_action.triggered.connect(self.showNormal)
        self.tray_menu.addAction(self.restore_action)
        self.minimize_action = QAction("最小化", self)
        self.minimize_action.triggered.connect(self.hide)
        self.tray_menu.addAction(self.minimize_action)
        self.quit_action = QAction("退出", self)
        self.quit_action.triggered.connect(self.quitApp)
        self.tray_menu.addAction(self.quit_action)
        self.tray_icon.setContextMenu(self.tray_menu)
 
        # 设置系统托盘图标的响应行为
        self.tray_icon.activated.connect(self.trayIconActivated)
        self.tray_icon.show()
 
        # 设置定时器
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.preventSleep)
 
    def centerOnScreen(self):
        # 将窗口居中显示
        screen_geometry = QApplication.desktop().screenGeometry()
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        self.move(x, y)
 
    def onButtonClick(self):
        # 触发开始/停止按钮
        if not self.isRunning:
            self.isRunning = True
            self.button.setText('停止')
            self.startTimer()
            self.hide()
        else:
            self.isRunning = False
            self.button.setText('开始')
            self.stopTimer()
 
    def startTimer(self):
        # 开始定时器
        interval = int(self.lineEdit.text())
        self.timer.start(interval * 1000)  # 将秒转换为毫秒
 
    def stopTimer(self):
        # 停止定时器
        self.timer.stop()
 
    def preventSleep(self):
        # 防止计算机进入睡眠模式
        self.KERNEL.SetThreadExecutionState(self.PREVENT)
 
    def quitApp(self):
        # 退出应用
        self.timer.stop()
        QApplication.quit()
 
    def trayIconActivated(self, reason):
        # 系统托盘图标被激活时的行为
        if reason == QSystemTrayIcon.DoubleClick:
            self.showNormal()
 
    def closeEvent(self, event):
        # 关闭事件,当窗口关闭时将事件忽略,而是隐藏窗口,除非系统托盘图标不可见
        if self.tray_icon.isVisible():
            event.ignore()
            self.hide()
        else:
            event.accept()
 
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
 
    mywindow = MyWindow()
    mywindow.show()
 
    sys.exit(app.exec_())

打包

pyinstaller --add-data "icon.png;." -F -i icon.ico script.py --noconsole

script.py是我的代码文件
icon.png是程序启动后显示的图标
-i icon.ico是用于指定程序的图标
--noconsole 运行时不显示控制台
图标文件与script.py文件在一个目录下,打包完成后生成build和dist两个目录,运行dist下面的.exe执行文件即可。

posted @ 2023-11-21 10:56  树苗叶子  阅读(354)  评论(0编辑  收藏  举报