使用Python实现一键隐藏屏幕并锁定输入

2025-04-08 15:50

本文主要是介绍使用Python实现一键隐藏屏幕并锁定输入,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《使用Python实现一键隐藏屏幕并锁定输入》本文主要介绍了使用Python编写一个一键隐藏屏幕并锁定输入的黑科技程序,能够在指定热键触发后立即遮挡屏幕,并禁止一切键盘鼠标输入,这样就再也不用担心自己...

1. 概述

你是否曾在办公时被人从背后偷看屏幕?或者在咖啡厅、图书馆等公共场合不想让别人看到你的私人内容?今天,我们将带你使用 python 编写一个一键隐藏屏幕并锁定输入的黑科技程序,能够在指定热键触发后立即遮挡屏幕,并禁止一切键盘鼠标输入。

这款工具基于 Tkinter 和 pynput,不仅能够全屏覆盖你的电脑,还支持自定义遮罩图片和文本,无论是工作还是娱乐,都能帮你有效防止信息泄露。

接下来,我们将详细讲解其功能、代码实现,并带你手把手打造属于你的专属隐私屏!

2. 功能亮点

本项目具备以下核心功能:

一键触发隐私屏 :用户可以自定义触发热键(默认 Ctrl + Menu),快速激活或隐藏隐私屏。

全屏黑色遮罩 :当触发后,屏幕会变成黑色,并阻止用户查看当前内容。

自定义遮罩内容 :

  • 可选择图片(如公司 Logo)作为屏保;
  • 可设置文本(如“请勿打扰”)。

输入锁定 :程序运行时,键盘和鼠标都会被禁用,确保电脑处于“冻结”状态。

后台日志记录 :所有操作都会被记录,方便调试与监控。

3.代码实现

以下是完整的 Python 代码:

import sys
import os
import ctypes
import tkinter as tk
import datetime
import threading
import time
from tkinter import Label
from PIL import Image, ImageTk
import configparser
from pynput import keyboard
import logging
from logging.handlers import TimedRotatingFileHandler

# 设置日志
def setup_logging():
    log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    log_file = os.path.join(log_dir, 'app.log')
    handler = TimedRotatingFileHandler(
        log_file, when="midnight", interval=js1, backupCount=31, encoding='utf-8'
    )
    handler.suffix = "%Y-%m-%d.log"
    formatter = logging.Formatter('[%(asctime)s] %(message)s', datefmt='%H:%M:%S')
    handler.setFormatter(formatter)
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)

setup_logging()

screen_visible = False
hotkey_combination = []
show_debugger = False
_blocking_thread = None
_stop_blocking = False

def _lock_input_periodically(screen = None):
    global _stop_blocking, hotkey_combination
    while not _stop_blocking:
        ctypes.windll.user32.BlockInput(True)
        screen and screen.getFocus()

        set_keys = set(hotkey_combination)
        if {'Ctrl_l', 'Ctrl_r'} & set_keys and {'Alt_l', 'Alt_gr'} & set_keys and 'Delete' in set_keys:
            hotkey_combination = [k for k in hotkey_combination if k not in {'Ctrl_l', 'Ctrl_r', 'Alt_l', 'Alt_gr', 'Delete'}]

        if show_debugger:
            logging.debug("输入&焦点 锁定")
        time.sleep(0.5)

class PrivacyScreen:
    def __init__(self, root, config):
        start_time = datetime.datetime.now()
        self.root = root
        self.config = config
        self.initUI()
        elapsed_time = (datetime.datetime.now() - start_time).total_seconds()
        logging.debug(f"创建完成 - {elapsed_time}s")

    def initUI(self):
        logging.debug("开始初始化窗口")
        self.root.attributes('-fullscreen', True)
        self.root.configure(background='black')
        self.root.attributes('-topmost', True)
        self.root.bind("<Escape>", lambda e: None)
        self.root.config(cursor="none")

        self.center_frame = tk.Frame(self.root, bg='black')
        self.center_frame.pack(expand=True, fill="both")

        widgets = []

        if 'covimg' in self.config and self.config['covimg'] != '':
            image_path = self.config['covimg']
            if os.path.exists(image_path):
                try:
                    logging.debug(f"加载图片 - {image_path}")
                    image = Image.open(image_path)
                    self.image = ImageTk.PhotoImage(image)
                    self.image_label = Label(self.center_frame, image=self.image, bg="black")
                    widgets.append(self.image_label)
                except Exception as e:
                    lwww.chinasem.cnogging.error(f"图片错误 - {e}")
        if 'covtxt' in self.config and self.config['covtxt'] != '':
            text = self.config['covtxt']
            self.text_label = Label(self.center_frame, text=text, fg='#999', bg='black', font=('Microsoft YaHei', 48, 'bold'))
            widgets.append(self.text_label)
        
        if len(widgets) == 2:
            y_offset = -60
        else:
            y_offset = 0
        if len(widgets) > 0:
            for i, widget in enumerate(widgets):
                widget.place(relx=0.5, rely=0.5, anchor="center", y=y_offset)
                y_offset += 215

    def showScreen(self):
        global screen_visible
        screen_visible = True
        self.root.deiconify()
        block_input(True, self)
        logging.debug("绘制组件 - ■")

    def hideScreen(self):
        global screen_visible
        screen_visible = False
        self.root.withdraw()
        block_input(False)
        logging.debug("绘制组件 - □")

    def getFocus(self):
        self.root.focus_force()

def get_log_time():
    return datetime.datetime.now().strftime("%H:%M:%S")

def block_input(block, screen = None):
    global _blocking_thread, _stop_blocking
    try:
        logging.debug(f"阻塞输入 - {'■' if block else '□'}")
        if block:
            if _blocking_thread is None or not _blocking_thread.is_alive():
                _stop_blocking = False
                _blocking_thread = threading.Thread(target=_lock_input_periodically, args=(screen,))
                _blocking_thread.daemon = True
                _blocking_thread.start()
        else:
            _stop_blocking = True
            if _blocking_thread is not None and _blocking_thread.is_alive():
                _blocking_thread.join()
            ctypes.windll.user32.BlockInput(False)
    except Exception as e:
        logging.error(f"阻塞失败 - {e}")

def toggle_privacy_screen(screen):
    if screen_visible:
        logging.debug("隐私窗口 - □")
        screen.hideScreen()
    else:
        loggiChina编程ng.debug("隐私窗口 - ■")
        screen.showScreen()

def get_config_path():
    if hasattr(sys, '_MEIPASS'):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(base_path, 'psc.conf')
    logging.debug(f"配置文件路径: {config_path}")
    return config_path

def read_config():
    config = configparser.ConfigParser()
    cohttp://www.chinasem.cnnfig_file = get_config_path()

    if not os.path.exists(config_file):
        logging.error(f"配置丢失: {config_file}")
        sys.exit(1)

    with open(config_file, 'r', encoding='utf-8') as f:
        logging.debug("读取配置 - Start")
        config.read_file(f)

    settings = {
        'hotkey': config.get('DEFAULT', 'hotkey', fallback='Ctrl_r+Menu'),
        'covimg': config.get('DEFAULT', 'covimg', fallback=''),
        'covtxt': config.get('DEFAULT', 'covtxt', fallback='该设备已锁定'),
        'strict': config.get('DEFAULT', 'strict', fallback=True),
        'debugs': config.get('DEFAULT', 'debugs', fallback=False)
    }
    settings['strict'] = str(settings['strict']).lower() == 'true' or settings['strict'] == '1'
    settings['debugs'] = str(settings['debugs']).lower() == 'true' or settings['debugs'] == '1'

    global show_debugger
    show_debugger = settings['debugs']

    logging.debug(f"配置加载 - Success")
    logging.debug(f"配置内容 - {settings}")
    return settings

def parse_hotkey(hotkey_str):
    keys = hotkey_str.split('+')
    logging.debug(f"解析热键: {hotkey_str} -> {keys}")
    return [key.strip() for key in keys]

def convert_special_key(input_string):
    return "" if any(f'F{i}' in input_string.upper() for i in range(13, 25)) else ''.join(chr(ord(c) + 64) if 1 <= ord(c) <= 26 else c for c in input_string or "")

def register_hotkey(hotkey, callback, strict):
    def on_press(key):
        global hotkey_combination
        try:
            key_name = convert_special_key(key.char if hasattr(key, 'char') else key.name)
            if key_name:
                key_name = key_name.capitalize()
                if key_name not in hotkey_combination:
                    hotkey_combination.append(key_name)
                if show_debugger:
                    logging.debug(f"i 按键 - ■ - {key_name}    当前 - {hotkey_combination}")
                if strict == 0:
                    if all(k in hotkey_combination for k in hotkey):
                        logging.info("★ 热键触发")
                        callback()
                else:
                    if sorted(hotkey_combination) == sorted(hotkey):
                        logging.info("★ 热键触发")
                        callback()
        except AttributeError:
            pass

    def on_release(key):
        global hotkey_combination
        try:
            key_name = convert_special_key(key.char if hasattr(key, 'char') else key.name)
            if key_name:
                key_name = key_name.capitalize()
                if key_name in hotkey_combination:
                    hotkey_combination.remove(key_name)
                    if key_name.startswith("Shift") and all(len(i) == 1 for i in hotkey_combination):
                        hotkey_combination = []
                if show_debugger:
                    logging.debug(f"i 按键 - □ - {key_name}    当前 - {hotkey_combination}")
        except AttributeError:
            pass

    listener = keyboard.Listener(on_press=on_press, on_release=on_release)
    listener.start()
    logging.debug("键盘监听 - Running")
    return listener

def main():
    logging.debug("")
    logging.debug("# ========== 程序启动 ========== #")
    logging.debug("")
    try:
        config = read_config()
        hotkey = parse_hotkey(config['hotkey'])

        root = tk.Tk()
        root.withwww.chinasem.cndraw()
        privacy_screen = PrivacyScreen(root, config)

        register_hotkey(hotkey, lambda: toggle_privacy_screen(privacy_screen), config['strict'])
        root.mainloop()
    except Exception as e:
        logging.error(f"未知异常 - {e}", exc_info=True)
        raise

if __name__ == "__main__":
    main()

代码解析:

日志管理:程序会在 logs/ 目录下自动创建日志文件,按日期存储。

热键监听:使用 pynput 监听键盘输入,检测到特定按键组合时触发屏幕遮罩。

隐私屏 UI:

  • 采用 Tkinter 全屏窗口,背景黑色。
  • 支持加载本地图片和文本。

键盘鼠标锁定:调用 ctypes.windll.user32.BlockInput(True) 禁用所有输入。

配置文件 **psc.conf**:

hotkey:设置触发热键。

covimg:遮罩图片路径。

covtxt:遮罩文本内容。

strict:是否启用严格模式。

debugs:是否开启调试信息。

4.使用方法

1. 运行环境

Windows 系统(目前仅支持 Windows,MAC/linux 需额外适配)

Python 3.7+

依赖库安装

pip install pillow pynput

2. 配置文件

创建 psc.conf 文件,填入以下内容:

[DEFAULT]
hotkey=Ctrl_r+Menu
covimg=
covtxt=该设备已锁定
strict=True
debugs=False

3. 运行程序

在终端执行:

python privacy_screen.py

按下 Ctrl + Menu 触发隐私屏,再次按下相同热键可解除。

5. 展示效果

使用Python实现一键隐藏屏幕并锁定输入

6. 代码优化与拓展

目前的版本已经实现了基础功能,后面将进行进行以下优化:

提升安全性:

  • 目前的 BlockInput(True) 在某些情况下可能会失效,可以结合 Windows API 进一步增强锁定能力。
  • 加密码解锁功能,防止误操作。

增强兼容性:

  • 适配 Mac 和 Linux,使用 Xlib 或 pyautogui 进行输入锁定。
  • 提供跨平台 GUI,如 PyQt。

新增远程控制:

  • 通过 Flask 或 WebSocket 远程控制隐私屏。
  • 在手机端发送指令激活/解除锁定。

7. 总结

本项目提供了一种便捷的隐私保护方案,适用于程序员、设计师、财务人员、商务人士等需要保护屏幕内容的用户。它具有 快速响应、完全遮挡、可定制、输入锁定 等特点,是一个实用的 Python 黑科技工具。

到此这篇关于使用Python实现一键隐藏屏幕并锁定输入的文章就介绍到这了,更多相关Python屏幕隐藏与锁定内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于使用Python实现一键隐藏屏幕并锁定输入的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154128

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环