返回列表 发布新帖

电脑定时锁屏软件V1.0

2213 0
小K网牛逼 发表于 2025-12-2 00:00:14 | 查看全部 阅读模式 <

马上注册,结交更多好友,享用更多功能,让你轻松玩转小K网。

您需要 登录 才可以下载或查看,没有账号?立即注册 微信登录

×
小孩玩电脑没有时间概念,所以用AI弄了这个定时锁屏软件,点击开始之后窗口会自动隐藏,只能通过快捷键Ctal+Alt+N+M调出窗口,倒计时还有10秒的时间,会弹窗提示

电脑定时锁屏软件V1.0

电脑定时锁屏软件V1.0


链接:https://pan.quark.cn/s/1ab222cd360f

下方是软件代码:

import tkinter as tk
from tkinter import messagebox, ttk
import threading
import time
import os
import sys
import ctypes
import keyboard
from datetime import datetime

class LockScreenApp:
def init(self, root):
self.root = root
self.root.title("电脑锁屏助手v1.0、吾爱首发")
self.root.geometry("400x350")
self.root.resizable(False, False)
self.root.attributes("-topmost", True)
  1.     # 设置窗口图标
  2.     try:
  3.         if hasattr(sys, '_MEIPASS'):
  4.             icon_path = os.path.join(sys._MEIPASS, 'icon.ico')
  5.         else:
  6.             icon_path = 'icon.ico'
  7.         if os.path.exists(icon_path):
  8.             self.root.iconbitmap(icon_path)
  9.     except Exception:
  10.         # 如果图标不存在或无法加载,忽略错误
  11.         pass
  12.     # 设置主题颜色 - 使用微信绿
  13.     self.bg_color = "#f0f0f0"
  14.     self.btn_color = "#07C160"  # 微信绿
  15.     self.btn_hover_color = "#06984e"  # 微信绿-深
  16.     self.text_color = "#333333"
  17.     self.root.configure(bg=self.bg_color)
  18.     # 初始化变量
  19.     self.lock_timer = None
  20.     self.is_timer_running = False
  21.     self.remaining_time = 0
  22.     self.paused_time = 0
  23.     self.is_paused = False
  24.     self.last_error = None
  25.     # 初始化窗口位置记忆
  26.     self.last_window_position = None
  27.     # 创建GUI组件
  28.     self.create_widgets()
  29.     # 设置全局热键
  30.     self.set_hotkey()
  31.     # 创建系统托盘图标
  32.     self.create_tray_icon()
  33. def create_widgets(self):
  34.     main_frame = ttk.Frame(self.root, padding="20")
  35.     main_frame.pack(fill=tk.BOTH, expand=True)
  36.     main_frame.configure(style="Main.TFrame")
  37.     style = ttk.Style()
  38.     style.configure("Main.TFrame", background=self.bg_color)
  39.     style.configure("TLabel", background=self.bg_color, foreground=self.text_color)
  40.     style.configure("Title.TLabel", font=("SimHei", 16, "bold"), background=self.bg_color, foreground=self.text_color)
  41.     style.configure("Subtitle.TLabel", font=("SimHei", 10), background=self.bg_color, foreground="#666666")
  42.     style.configure("Status.TLabel", font=("SimHei", 10), background=self.bg_color, foreground=self.text_color)
  43.     style.configure("Hotkey.TLabel", font=("SimHei", 8), foreground="#666666", background=self.bg_color)
  44.     style.configure("TButton", font=("SimHei", 10))
  45.     title_frame = ttk.Frame(main_frame)
  46.     title_frame.pack(fill=tk.X, pady=(0, 15))
  47.     title_frame.configure(style="Main.TFrame")
  48.     title_label = ttk.Label(title_frame, text="电脑锁屏助手", style="Title.TLabel")
  49.     title_label.pack(side=tk.LEFT)
  50.     def create_custom_button(parent, text, command, width=5):
  51.         btn = tk.Button(
  52.             parent,
  53.             text=text,
  54.             font=("SimHei", 11, "bold"),
  55.             bg=self.btn_color,
  56.             fg="white",
  57.             activebackground=self.btn_hover_color,
  58.             activeforeground="white",
  59.             relief=tk.RAISED,
  60.             bd=0,
  61.             highlightthickness=0,
  62.             padx=10,
  63.             pady=10,
  64.             width=width,
  65.             command=command
  66.         )
  67.         btn.configure(highlightbackground=self.btn_color, highlightcolor=self.btn_color, highlightthickness=0)
  68.         btn.bind("<Enter>", lambda e, b=btn: b.config(bg=self.btn_hover_color))
  69.         btn.bind("<Leave>", lambda e, b=btn: b.config(bg=self.btn_color))
  70.         btn.bind("<ButtonPress-1>", lambda e, b=btn: b.config(bg="#004080"))
  71.         btn.bind("<ButtonRelease-1>", lambda e, b=btn: b.config(bg=self.btn_hover_color))
  72.         return btn
  73.     # 时间选择器区域 - 放在上面一行
  74.     time_select_frame = ttk.Frame(main_frame)
  75.     time_select_frame.pack(fill=tk.X, pady=15)
  76.     time_select_frame.configure(style="Main.TFrame")
  77.     # 5分钟按钮
  78.     self.btn_5min = create_custom_button(time_select_frame, "5分钟", lambda: self.start_timer(5), width=3)
  79.     self.btn_5min.pack(side=tk.LEFT, padx=10, pady=5)
  80.     # 10分钟按钮
  81.     self.btn_10min = create_custom_button(time_select_frame, "10分钟", lambda: self.start_timer(10), width=4)
  82.     self.btn_10min.pack(side=tk.LEFT, padx=10, pady=5)
  83.     # 自定义时间输入区域
  84.     custom_frame = ttk.Frame(time_select_frame)
  85.     custom_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=10)
  86.     custom_frame.configure(style="Main.TFrame")
  87.     self.custom_time_var = tk.StringVar()
  88.     self.custom_time_entry = ttk.Entry(
  89.         custom_frame,
  90.         textvariable=self.custom_time_var,
  91.         width=4,
  92.         font=(("SimHei", 22))
  93.     )
  94.     self.custom_time_entry.pack(side=tk.LEFT, padx=(0, 5), pady=2)
  95.     self.custom_time_entry.bind("<KeyRelease>", self.validate_time_input)
  96.     self.custom_time_entry.bind("<Return>", lambda event: self.start_custom_timer())
  97.     ttk.Label(custom_frame, text="分钟", font=(("SimHei", 20))).pack(side=tk.LEFT, padx=2)
  98.     # 按钮操作区域 - 放在下面一行
  99.     action_frame = ttk.Frame(main_frame)
  100.     action_frame.pack(fill=tk.X, pady=10)
  101.     action_frame.configure(style="Main.TFrame")
  102.     # 开始按钮
  103.     self.btn_start = create_custom_button(action_frame, "开始", self.start_custom_timer, width=6)
  104.     self.btn_start.pack(side=tk.LEFT, padx=10, pady=5)
  105.     # 暂停/继续按钮
  106.     self.btn_pause = create_custom_button(action_frame, "暂停/继续", self.toggle_pause, width=8)
  107.     self.btn_pause.pack(side=tk.LEFT, padx=10, pady=5)
  108.     # 新增清空按钮
  109.     self.btn_clear = create_custom_button(action_frame, "清空", self.cancel_timer, width=6)
  110.     self.btn_clear.pack(side=tk.LEFT, padx=10, pady=5)
  111.     status_frame = ttk.Frame(main_frame)
  112.     status_frame.pack(fill=tk.X, pady=15)
  113.     status_frame.configure(style="Main.TFrame")
  114.     ttk.Label(status_frame, text="状态:", style="TLabel").pack(side=tk.LEFT)
  115.     self.status_var = tk.StringVar()
  116.     self.status_var.set("就绪")
  117.     self.status_label = ttk.Label(status_frame, textvariable=self.status_var, style="Status.TLabel")
  118.     self.status_label.pack(side=tk.LEFT, padx=5)
  119.     bottom_frame = ttk.Frame(main_frame)
  120.     bottom_frame.pack(fill=tk.X, side=tk.BOTTOM)
  121.     bottom_frame.configure(style="Main.TFrame")
  122.     hotkey_label = ttk.Label(bottom_frame, text="Ctrl+Alt+N+M 调出窗口", style="Hotkey.TLabel")
  123.     hotkey_label.pack(pady=(10, 0))
  124. def start_timer(self, minutes):
  125.     """启动倒计时计时器"""
  126.     try:
  127.         if self.is_timer_running:
  128.             # 取消当前计时器
  129.             self.cancel_timer()
  130.         # 设置新的倒计时时间
  131.         self.remaining_time = minutes * 60
  132.         self.is_timer_running = True
  133.         self.is_paused = False
  134.         # 更新状态
  135.         self.status_var.set(f"锁屏将在 {minutes} 分钟后启动")
  136.         self.update_tray_tooltip(f"锁屏将在 {minutes} 分钟后启动")
  137.         # 记录启动事件
  138.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  139.             f.write(f"计时器启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, 设定时间: {minutes}分钟\n")
  140.         # 创建并启动计时器线程
  141.         self.lock_timer = threading.Thread(target=self.countdown)
  142.         self.lock_timer.daemon = True
  143.         self.lock_timer.start()
  144.         # 隐藏窗口
  145.         self.hide_window()
  146.     except Exception as e:
  147.         # 记录启动错误
  148.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  149.             f.write(f"启动计时器错误: {str(e)}\n")
  150.         messagebox.showerror("错误", f"启动计时器时出错: {str(e)}")
  151. def validate_time_input(self, event=None):
  152.     """验证时间输入,只允许数字和小数点,最多480分钟"""
  153.     input_text = self.custom_time_var.get()
  154.     # 移除非数字和小数点的字符
  155.     new_text = ''.join(c for c in input_text if c.isdigit() or c == '.')
  156.     # 确保只有一个小数点
  157.     if new_text.count('.') > 1:
  158.         parts = new_text.split('.')
  159.         new_text = parts[0] + '.' + ''.join(parts[1:])
  160.     # 更新输入框
  161.     if new_text != input_text:
  162.         self.custom_time_var.set(new_text)
  163.         # 保持光标位置
  164.         pos = event.widget.index(tk.INSERT)
  165.         event.widget.icursor(pos - (len(input_text) - len(new_text)))
  166.     # 检查是否超过480分钟(8小时)
  167.     try:
  168.         if new_text:
  169.             minutes = float(new_text)
  170.             if minutes > 480:
  171.                 self.custom_time_var.set('480')
  172.                 self.status_var.set("警告: 超过最大时间限制")
  173.             else:
  174.                 self.status_var.set("就绪")
  175.     except ValueError:
  176.         pass
  177. def start_custom_timer(self):
  178.     """从输入框启动自定义时间计时"""
  179.     try:
  180.         time_str = self.custom_time_var.get()
  181.         if not time_str:
  182.             messagebox.showwarning("输入错误", "请输入时间")
  183.             return
  184.         minutes = float(time_str)
  185.         if minutes <= 0:
  186.             messagebox.showwarning("输入错误", "请输入大于0的时间")
  187.             return
  188.         if minutes > 480:
  189.             messagebox.showwarning("输入错误", "最大时间为480分钟")
  190.             return
  191.         # 保留浮点数,但设置最小时间为0.1分钟(6秒)
  192.         if minutes < 0.1:
  193.             minutes = 0.1  # 最少0.1分钟
  194.         self.start_timer(minutes)
  195.     except ValueError:
  196.         messagebox.showwarning("输入错误", "请输入有效的数字")
  197.         self.custom_time_entry.focus_set()
  198. def toggle_pause(self):
  199.     """暂停或恢复计时器"""
  200.     if not self.is_timer_running:
  201.         messagebox.showinfo("提示", "计时器未运行")
  202.         return
  203.     if self.is_paused:
  204.         # 恢复计时器
  205.         self.is_paused = False
  206.         self.btn_pause.config(text="暂停/继续")
  207.         self.btn_pause.config(bg=self.btn_color, fg="white", activebackground=self.btn_hover_color)
  208.         time_text = self.format_time(self.remaining_time)
  209.         self.status_var.set(f"恢复倒计时,剩余时间: {time_text}")
  210.         self.update_tray_tooltip(f"恢复倒计时: {time_text}")
  211.         # 继续倒计时线程
  212.         self.lock_timer = threading.Thread(target=self.countdown)
  213.         self.lock_timer.daemon = True
  214.         self.lock_timer.start()
  215.         # 记录恢复事件
  216.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  217.             f.write(f"计时器恢复时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, 剩余时间: {time_text}\n")
  218.     else:
  219.         # 暂停计时器
  220.         self.is_paused = True
  221.         self.btn_pause.config(text="继续")
  222.         self.btn_pause.config(bg="#ffc107", fg="#333333", activebackground="#e0a800")
  223.         time_text = self.format_time(self.remaining_time)
  224.         self.status_var.set(f"已暂停,剩余时间: {time_text}")
  225.         self.update_tray_tooltip(f"已暂停: {time_text}")
  226.         # 记录暂停事件
  227.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  228.             f.write(f"计时器暂停时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, 剩余时间: {time_text}\n")
  229. def countdown(self):
  230.     """倒计时线程函数"""
  231.     try:
  232.         # 记录倒计时开始
  233.         start_time = time.time()
  234.         target_time = start_time + self.remaining_time
  235.         # 清除可能存在的警告窗口引用
  236.         if hasattr(self, '_warning_window'):
  237.             if self._warning_window.winfo_exists():
  238.                 self._warning_window.destroy()
  239.         while self.is_timer_running and not self.is_paused:
  240.             # 计算剩余时间(更准确的计时方式)
  241.             current_time = time.time()
  242.             self.remaining_time = int(target_time - current_time)
  243.             if self.remaining_time <= 0:
  244.                 break
  245.             # 更新状态和托盘提示
  246.             time_text = self.format_time(self.remaining_time)
  247.             # 使用线程安全的方式更新GUI
  248.             self.root.after(0, lambda tt=time_text: self.status_var.set(f"剩余时间: {tt}"))
  249.             self.update_tray_tooltip(f"剩余时间: {time_text}")
  250.             # 添加倒计时提示功能(10秒及以内)
  251.             if 0 < self.remaining_time <= 10:
  252.                 # 使用线程安全的方式显示或更新提示框
  253.                 self.root.after(0, lambda remaining=self.remaining_time: self._show_lock_warning(remaining))
  254.             # 休眠1秒,但可以被中断
  255.             for _ in range(10):  # 分成10次小休眠,以便更快响应暂停/取消
  256.                 if not self.is_timer_running or self.is_paused:
  257.                     break
  258.                 time.sleep(0.1)
  259.             # 检查是否被暂停或取消
  260.             if not self.is_timer_running or self.is_paused:
  261.                 break
  262.         # 倒计时结束,执行锁屏
  263.         if self.remaining_time <= 0 and self.is_timer_running and not self.is_paused:
  264.             self.lock_screen()
  265.     except Exception as e:
  266.         # 记录倒计时错误
  267.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  268.             f.write(f"倒计时错误: {str(e)}\n")
  269.         # 尝试锁屏作为安全措施
  270.         try:
  271.             self.lock_screen()
  272.         except:
  273.             pass
  274. def format_time(self, seconds):
  275.     """格式化时间为分:秒"""
  276.     minutes = seconds // 60
  277.     secs = seconds % 60
  278.     return f"{minutes:02d}:{secs:02d}"
  279. def _show_lock_warning(self, remaining):
  280.     """显示锁屏前的警告提示,支持动态更新倒计时"""
  281.     # 检查是否已存在警告窗口,如果存在则更新内容,否则创建新窗口
  282.     if hasattr(self, '_warning_window') and self._warning_window.winfo_exists():
  283.         # 更新现有窗口的标签文本
  284.         if hasattr(self, '_warning_label'):
  285.             self._warning_label.config(text=f"电脑还有 {remaining} 秒锁屏了")
  286.     else:
  287.         # 创建一个独立的提示窗口
  288.         self._warning_window = tk.Toplevel(self.root)
  289.         self._warning_window.title("锁屏警告")
  290.         self._warning_window.geometry("300x150")
  291.         self._warning_window.attributes("-topmost", True)
  292.         self._warning_window.configure(bg="#f0f0f0")
  293.         # 居中窗口
  294.         self._warning_window.update_idletasks()
  295.         width = self._warning_window.winfo_width()
  296.         height = self._warning_window.winfo_height()
  297.         x = (self._warning_window.winfo_screenwidth() // 2) - (width // 2)
  298.         y = (self._warning_window.winfo_screenheight() // 2) - (height // 2)
  299.         self._warning_window.geometry(f"{width}x{height}+{x}+{y}")
  300.         # 添加提示标签
  301.         self._warning_label = tk.Label(
  302.             self._warning_window,
  303.             text=f"电脑还有 {remaining} 秒锁屏了",
  304.             font=("SimHei", 16, "bold"),
  305.             bg="#f0f0f0",
  306.             fg="#ff0000"
  307.         )
  308.         self._warning_label.pack(pady=20)
  309.         # 添加关闭按钮
  310.         btn_ok = tk.Button(
  311.             self._warning_window,
  312.             text="知道了",
  313.             font=("SimHei", 12),
  314.             bg=self.btn_color,
  315.             fg="white",
  316.             activebackground=self.btn_hover_color,
  317.             relief=tk.RAISED,
  318.             bd=0,
  319.             padx=20,
  320.             pady=8,
  321.             command=self._warning_window.destroy
  322.         )
  323.         btn_ok.pack(pady=10)
  324.         btn_ok.configure(highlightbackground=self.btn_color, highlightthickness=0)
  325. def lock_screen(self):
  326.     """锁定屏幕(支持多种锁屏方式作为备选)"""
  327.     try:
  328.         # 记录锁屏时间
  329.         lock_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  330.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  331.             f.write(f"屏幕锁定时间: {lock_time}\n")
  332.         # 方法1: 使用Windows API (首选方法)
  333.         try:
  334.             result = ctypes.windll.user32.LockWorkStation()
  335.             if result:
  336.                 with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  337.                     f.write("锁屏成功: 使用Windows API\n")
  338.             else:
  339.                 raise Exception("LockWorkStation API 调用失败")
  340.         except Exception as e1:
  341.             # 记录首选方法失败
  342.             with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  343.                 f.write(f"首选锁屏方法失败: {str(e1)}\n")
  344.             # 方法2: 使用rundll32命令
  345.             try:
  346.                 import subprocess
  347.                 subprocess.run(["rundll32.exe", "user32.dll,LockWorkStation"],
  348.                               shell=True, check=True)
  349.                 with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  350.                     f.write("锁屏成功: 使用rundll32命令\n")
  351.             except Exception as e2:
  352.                 # 记录方法2失败
  353.                 with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  354.                     f.write(f"备用锁屏方法失败: {str(e2)}\n")
  355.                 # 方法3: 使用PowerShell命令
  356.                 try:
  357.                     import subprocess
  358.                     powershell_command = "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('^({ESC}{TAB}{ESC})')"
  359.                     subprocess.run(["powershell.exe", "-Command", powershell_command],
  360.                                   shell=True, check=True)
  361.                     with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  362.                         f.write("锁屏成功: 使用PowerShell命令\n")
  363.                 except Exception as e3:
  364.                     # 所有方法都失败
  365.                     with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  366.                         f.write(f"所有锁屏方法都失败: {str(e3)}\n")
  367.                     # 显示消息提示用户手动锁屏
  368.                     messagebox.showwarning(
  369.                         "锁屏失败",
  370.                         "无法自动锁定屏幕。请手动锁定您的计算机。\n" +
  371.                         "锁屏时间: " + lock_time
  372.                     )
  373.         # 重置状态
  374.         self.reset_timer()
  375.     except Exception as e:
  376.         # 记录总错误
  377.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  378.             f.write(f"锁屏过程总错误: {str(e)}\n")
  379.         # 即使出错也要重置状态
  380.         self.reset_timer()
  381. def reset_timer(self):
  382.     """重置计时器状态"""
  383.     self.is_timer_running = False
  384.     self.is_paused = False
  385.     self.remaining_time = 0
  386.     self.btn_pause.config(text="暂停")
  387.     self.status_var.set("就绪")
  388.     self.update_tray_tooltip("就绪")
  389. def cancel_timer(self):
  390.     """取消当前计时器"""
  391.     # 确保线程安全地停止
  392.     self.is_timer_running = False
  393.     self.is_paused = False
  394.     self.remaining_time = 0
  395.     # 重置UI状态
  396.     self.btn_pause.config(text="暂停")
  397.     self.status_var.set("就绪")
  398.     self.update_tray_tooltip("就绪")
  399.     # 如果有正在运行的计时器线程,尝试让它自然结束
  400.     # 注意:Python中不能强制终止线程,而是通过标志位让它自己退出
  401.     # 额外确保界面可见,用户能看到取消后的状态
  402.     self.show_window()
  403.     # 记录取消事件
  404.     try:
  405.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  406.             f.write(f"计时器取消时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
  407.     except Exception as e:
  408.         # 即使日志写入失败,也要确保功能正常
  409.         pass
  410. def hide_window(self):
  411.     """隐藏窗口"""
  412.     # 保存当前窗口位置
  413.     try:
  414.         x = self.root.winfo_x()
  415.         y = self.root.winfo_y()
  416.         if x > 0 and y > 0:  # 确保位置有效
  417.             self.last_window_position = (x, y)
  418.     except:
  419.         pass  # 忽略获取位置时的错误
  420.     # 完全隐藏窗口(不仅是最小化)
  421.     self.root.withdraw()
  422.     # 在系统托盘显示消息
  423.     try:
  424.         self.tray_icon.showmessage(
  425.             "锁屏助手",
  426.             "程序已在后台运行\n按 Ctrl+Alt+N+M 调出窗口",
  427.             timeout=5000
  428.         )
  429.     except:
  430.         pass  # 忽略托盘错误
  431. def show_window(self):
  432.     """显示窗口"""
  433.     try:
  434.         # 从隐藏状态恢复
  435.         self.root.deiconify()
  436.         # 确保窗口在最上层
  437.         self.root.attributes("-topmost", True)
  438.         self.root.attributes("-topmost", False)  # 允许其他窗口也能成为顶层
  439.         # 激活窗口
  440.         self.root.focus_force()
  441.         # 检查是否有保存的窗口位置,如果没有则居中显示
  442.         if not hasattr(self, 'last_window_position'):
  443.             # 计算屏幕中心位置
  444.             screen_width = self.root.winfo_screenwidth()
  445.             screen_height = self.root.winfo_screenheight()
  446.             window_width = 400  # 窗口宽度
  447.             window_height = 350  # 窗口高度
  448.             x = (screen_width - window_width) // 2
  449.             y = (screen_height - window_height) // 2
  450.             # 设置窗口位置并保存
  451.             self.root.geometry(f"+{x}+{y}")
  452.             self.last_window_position = (x, y)
  453.         else:
  454.             # 使用之前保存的位置
  455.             x, y = self.last_window_position
  456.             self.root.geometry(f"+{x}+{y}")
  457.     except Exception as e:
  458.         # 记录错误但不显示,避免影响用户体验
  459.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  460.             f.write(f"显示窗口错误: {str(e)}\n")
  461. def create_tray_icon(self):
  462.     """创建系统托盘图标"""
  463.     try:
  464.         # 尝试导入并创建系统托盘图标
  465.         import pystray
  466.         from pystray import MenuItem as item
  467.         from PIL import Image, ImageDraw
  468.         # 创建一个简单的图标
  469.         def create_image():
  470.             width = 64
  471.             height = 64
  472.             color1 = "#0078d7"
  473.             color2 = "white"
  474.             # 创建空白图像
  475.             image = Image.new('RGB', (width, height), color1)
  476.             dc = ImageDraw.Draw(image)
  477.             # 绘制简单的锁图标
  478.             dc.rectangle([10, 25, 54, 45], fill=color2)
  479.             dc.rectangle([25, 15, 39, 35], fill=color2)
  480.             dc.ellipse([20, 10, 44, 20], fill=color1, outline=color2, width=3)
  481.             return image
  482.         # 创建菜单
  483.         menu = (
  484.             item('显示窗口', self.show_window),
  485.             item('暂停/恢复', self.toggle_pause),
  486.             item('退出', self.on_closing)
  487.         )
  488.         # 创建托盘图标
  489.         self.tray_icon = pystray.Icon("LockScreen", create_image(), "锁屏助手", menu)
  490.         # 在单独的线程中运行托盘图标
  491.         self.tray_thread = threading.Thread(target=self.tray_icon.run, daemon=True)
  492.         self.tray_thread.start()
  493.     except ImportError:
  494.         # 如果没有安装pystray,使用tkinter的简化方法
  495.         self.tray_icon = None
  496.         pass
  497. def update_tray_tooltip(self, message):
  498.     """更新系统托盘提示文本"""
  499.     try:
  500.         if hasattr(self, 'tray_icon') and self.tray_icon:
  501.             self.tray_icon.title = f"锁屏助手 - {message}"
  502.     except:
  503.         pass  # 忽略托盘错误
  504. def set_hotkey(self):
  505.     """设置全局热键"""
  506.     try:
  507.         # 移除可能已存在的热键(避免重复设置)
  508.         try:
  509.             keyboard.remove_hotkey('ctrl+alt+n+m')
  510.         except:
  511.             pass
  512.         # 设置组合热键 Ctrl+Alt+N+M
  513.         keyboard.add_hotkey('ctrl+alt+n+m', self.show_window)
  514.         # 记录热键设置成功
  515.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  516.             f.write(f"热键设置成功: Ctrl+Alt+N+M\n")
  517.     except Exception as e:
  518.         # 记录错误
  519.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  520.             f.write(f"热键设置失败: {str(e)}\n")
  521.         # 尝试使用备用方案
  522.         try:
  523.             # 备用方案:使用全局钩子监听按键事件
  524.             def on_key_event(event):
  525.                 # 检查是否按下了Ctrl+Alt+N+M组合键
  526.                 if event.name == 'm' and keyboard.is_pressed('ctrl') and keyboard.is_pressed('alt') and keyboard.is_pressed('n'):
  527.                     self.show_window()
  528.             # 监听所有按键事件
  529.             keyboard.on_press(on_key_event)
  530.             # 记录备用方案设置成功
  531.             with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  532.                 f.write("备用热键方案设置成功\n")
  533.         except Exception as e2:
  534.             # 记录备用方案失败
  535.             with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  536.                 f.write(f"备用热键方案设置失败: {str(e2)}\n")
  537.             # 显示警告消息
  538.             messagebox.showwarning(
  539.                 "热键设置警告",
  540.                 "无法设置全局热键。请确保以管理员权限运行程序。\n" +
  541.                 "您仍然可以通过系统托盘图标访问程序。"
  542.             )
  543. def on_closing(self):
  544.     """窗口关闭事件处理"""
  545.     # 取消计时器
  546.     self.cancel_timer()
  547.     # 清理热键
  548.     try:
  549.         keyboard.unhook_all()
  550.     except:
  551.         pass
  552.     # 关闭托盘图标
  553.     try:
  554.         if hasattr(self, 'tray_icon') and self.tray_icon:
  555.             self.tray_icon.stop()
  556.     except:
  557.         pass
  558.     # 记录程序退出
  559.     with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  560.         f.write(f"程序退出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
  561.         f.write("="*50 + "\n")
  562.     # 关闭窗口
  563.     self.root.destroy()
  564. def check_environment(self):
  565.     """检查运行环境"""
  566.     try:
  567.         # 创建日志目录(如果不存在)
  568.         log_file = "lock_screen_log.txt"
  569.         # 写入程序启动信息
  570.         with open(log_file, "a", encoding="utf-8") as f:
  571.             f.write("="*50 + "\n")
  572.             f.write(f"程序启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
  573.             f.write(f"Python版本: {sys.version}\n")
  574.             f.write(f"操作系统: Windows\n")
  575.         # 检查是否以管理员权限运行
  576.         try:
  577.             is_admin = ctypes.windll.shell32.IsUserAnAdmin()
  578.             with open(log_file, "a", encoding="utf-8") as f:
  579.                 f.write(f"管理员权限: {'是' if is_admin else '否'}\n")
  580.         except:
  581.             with open(log_file, "a", encoding="utf-8") as f:
  582.                 f.write("无法检查管理员权限\n")
  583.     except Exception as e:
  584.         # 如果日志写入失败,尝试简单的异常处理
  585.         self.last_error = str(e)
  586.         pass
复制代码

  1.     try:
  2.         with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
  3.             f.write(f"未捕获异常: {exc_type.__name__}: {str(exc_value)}\n")
  4.             import traceback
  5.             traceback.print_tb(exc_traceback, file=f)
  6.             f.write("="*50 + "\n")
  7.     except:
  8.         pass  # 如果日志写入失败,忽略
  9. # 设置全局异常处理
  10. sys.excepthook = handle_exception
复制代码
  1. root = tk.Tk()
  2. # 创建应用实例
  3. app = LockScreenApp(root)
  4. # 运行应用
  5. root.mainloop()
复制代码

回复

您需要登录后才可以回帖 登录 | 立即注册 微信登录

本版积分规则

您需要 登录 后才可以回复,轻松玩转社区,没有帐号?立即注册
快速回复
关灯 在本版发帖
扫一扫添加微信客服
QQ客服返回顶部
快速回复 返回顶部 返回列表