How to prevent others from taking screenshots of your screen using Python? Here are six ways!

In this article, we will discuss six ways to prevent screenshots using Python.

These methods can help protect your application from attacks such as screenshots, screen recordings, or screen recordings.

These methods are not only used to protect your personal information and privacy, but they can also be used to protect valuable business information from being stolen.

Before discussing the specific implementation methods, we need to understand what anti-screenshot is.

Anti-screenshot refers to a set of techniques or methods used to prevent others from capturing or recording images on the screen without permission.

This is an important security measure that prevents the theft of sensitive information or the surveillance of personal information.

Here are six ways to implement screenshot-proofing for Python applications:

1. Pillow, ImageGrab

The Pillow library provides a module called “ImageGrab” that can be used to grab images from the screen.

While it is a useful library, it can also be used to take screenshots of your application.

To prevent this from happening, we can use the “grabclipboard” function from this library.

It will enhance your security by preventing screen images from being copied to the clipboard.

The following is sample code for using Pillow to prevent screenshots:

from PIL import ImageGrab
  
def test_screenshot():
    im = ImageGrab.grab()
    im.show()
  
# Use screenshot protection
def test_screenshot_protection():
    import win32clipboard
    try:
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.CloseClipboard()
        print("Clipboard cleared")
    except Exception as e:
        print(e)
  
    im = ImageGrab.grabclipboard()
    if im:
        im.show()

The code above shows how to use the ImageGrab module to capture a screen.

Please note that in the “test_screenshot_protection” function we clear the clipboard first and then use the “grabclipboard” function.

This ensures that the image is not copied to the clipboard, improving security.

2. pyautogui, screenshot

pyautogui is a powerful library for GUI automation. It contains some functions for taking screenshots.

Even if your program is not sharing the screen, it is still possible to capture the screen using these functions.

The following is sample code to prevent screenshots using pyautogui:

import pyautogui
  
def test_screenshot():
    pyautogui.screenshot("screenshot.png")
  
# Use screenshot protection
def test_screenshot_protection():
    import win32clipboard
    try:
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.CloseClipboard()
        print("Clipboard cleared")
    except Exception as e:
        print(e)
  
    pyautogui.FAILSAFE = False
    pyautogui.PAUSE=0
    image = pyautogui.screenshot()
    if image:
        image.show()

Similar to the first method, in the “test_screenshot_protection” function, we clear the clipboard and then use pyautogui’s screenshot function.

At the same time we set the two parameters of the pyautogui library to False and 0, this ensures that the program does not inadvertently interrupt and try to copy to the clipboard.

3. win32gui API screenshot

The win32gui API can be used to capture screenshots on Windows operating systems.

Therefore, if your program is running on Windows, other programs can also use these APIs to take screenshots.

To prevent this from happening, we can use these APIs to limit screenshots to a specific window.

The following is sample code to prevent screenshots using the win32gui API:

import win32gui
import win32ui
import win32con
import win32api
  
def capture_window(window_name):
    hwnd = win32gui.FindWindow(None, window_name)
    if hwnd != 0:
        l,t,r,b = win32gui.GetClientRect(hwnd)
        h = b - t + 1
        w = r - l + 1
  
        hDC = win32gui.GetWindowDC(hwnd)
        myDC = win32ui.CreateDCFromHandle(hDC)
        newDC = myDC.CreateCompatibleDC()
  
        myBitMap = win32ui.CreateBitmap()
        myBitMap.CreateCompatibleBitmap(myDC, w, h)
  
        newDC.SelectObject(myBitMap)
  
        win32gui.SetForegroundWindow(hwnd)
        newDC.BitBlt((0,0),(w, h) , myDC, (0, 0), win32con.SRCCOPY)
        myBitMap.SaveBitmapFile(newDC, bmp_file)
  
        win32gui.DeleteObject(myBitMap.GetHandle())
        newDC.DeleteDC()
        myDC.DeleteDC()
        win32gui.ReleaseDC(hwnd, hDC)

The above function can be used to capture screenshots within a specific window.

This function uses various win32gui APIs to get a handle to a specific window and capture a screenshot from that specific window.

So you can easily limit screenshots if the function only applies to the window your program is in.

4. pyhook monitor screen

The pyhook library can be used to monitor screen activities such as screenshots or screen recordings.

This library can listen for Windows messages and trigger events when screen activity is detected.

We can use these events to prevent screenshots or recordings.

The following is sample code for using pyhook to prevent screenshots:

import threading
import pyHook
import pythoncom
  
def on_mouse_event(event):
    if event.MessageName == 'mouse left down':
        print("Mouse click detected.")
        return False
    return True
  
def install_hook():
    hm = pyHook.HookManager()
    hm.MouseAllButtonsDown = on_mouse_event
    hm.HookMouse()
  
    pythoncom.PumpMessages()
  
# Start thread to monitor screen activity
def start_scanning():
    t = threading.Thread(target=install_hook)
    t.start()
    print("Hook installed")
  
# Stop screen scanning
def stop_scanning():
    pythoncom.PostQuitMessage(0)
    print("Hook removed")

The above code shows how to use the pyhook library.

In the “on_mouse_event” function we monitor mouse activity.

If a left mouse button click is detected, False is returned, preventing the screenshot.

Returns True if no activity is detected, allowing screenshots or recordings to be taken.

  1. OpenGL rendering screenshot

OpenGL rendering uses a hardware-accelerated graphics processor rather than using a CPU-based approach.

This means that the rendering process will not be recognized by screenshot tools.

Therefore, we can render the application’s graphics into an OpenGL context, thereby protecting the application while still being able to display the image.

Here is sample code to prevent screenshots using OpenGL:

from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *
  
def render():
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    gluPerspective(45, (640/480), 0.1, 50.0)
    glTranslatef(0.0, 0.0, -5.0)
    glColor3f(1.0, 1.0, 1.0)
    glBegin(GL_QUADS)
    glVertex3f(-1.0, 1.0, 0.0)
    glVertex3f(1.0, 1.0, 0.0)
    glVertex3f(1.0, -1.0, 0.0)
    glVertex3f(-1.0, -1.0, 0.0)
    glEnd()
  
def run():
    pygame.init()
    pygame.display.set_mode((640, 480), DOUBLEBUF|OPENGL)
    clock = pygame.time.Clock()
  
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                quit()
  
        render()
        pygame.display.flip()
        clock.tick(60)
  
run()

The above code demonstrates how to render an image using OpenGL. Using OpenGL to render images prevents them from being stolen.

  1. Dark mode or watermark

Dark mode and watermarks can both be used to prevent screenshots.

Dark mode turns a user’s screenshot into a useless black image.

Watermarks, on the other hand, prevent others from using your images for unauthorized commercial purposes.

Depending on the application scenario and needs, in order to implement dark mode or watermark, you can use the ImageDraw and ImageFont modules in the Pillow library.

Here is sample code to prevent screenshots using dark mode and watermarks:

from PIL import Image, ImageDraw, ImageFont
  
# dark mode
def dark_mode():
    image = Image.new('RGB', (500,500), color=(0,0,0))
    image.show()
  
# watermark
def add_watermark():
    image = Image.open("image.png")
  
    draw = ImageDraw.Draw(image)
    text = "Confidential"
    font = ImageFont.truetype("arial.ttf", 30)
    textwidth, texttheight = draw.textsize(text, font)
  
    # Place watermark
    x, y = image.size
    draw.text((x - textwidth - 10, y - textheight - 10), text, font=font)
    image.show()
Summary

In this article, we discuss six methods on how to prevent screenshots using Python.

Most of these methods rely on libraries or APIs in Python, such as Pillow, PyHook, and OpenGL.

Before implementing these techniques, make sure your application truly requires this additional security measure, and make sure you understand the best solution for your application.

About Python’s technical reserves

If you are planning to learn Python or are currently learning it, you should be able to use the following:

① A roadmap for learning Python in all directions, knowing what to learn in each direction
② More than 100 Python course videos, covering essential basics, crawlers and data analysis
③ More than 100 Python practical cases, learning is no longer just theory
④ Huawei’s exclusive Python comic tutorial, you can also learn it on your mobile phone
⑤Real Python interview questions from Internet companies over the years, very convenient for review

There are ways to get it at the end of the article

1. Learning routes in all directions of Python

The Python all-direction route is to organize the commonly used technical points of Python to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.

2. Python course video

When we watch videos and learn, we can’t just move our eyes and brain but not our hands. The more scientific learning method is to use them after understanding. At this time, hands-on projects are very suitable.

3. Python practical cases

Optical theory is useless. You must learn to follow along and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

4. Python comic tutorial

Use easy-to-understand comics to teach you to learn Python, making it easier for you to remember and not boring.

5. Internet company interview questions

We must learn Python to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and Alibaba bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.


This complete version of the complete set of Python learning materials has been uploaded to CSDN. If friends need it, you can also scan the official QR code of csdn below or click on the WeChat card at the bottom of the homepage and article to get the method. [Guaranteed 100% free]

syntaxbug.com © 2021 All Rights Reserved.