使用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

相关文章

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.