Have you ever wanted to use your monitor as a makeshift light source when your webcam is active? In this tutorial, we’ll create a Python script that detects when your webcam is in use and automatically changes your desktop wallpaper to a bright white image. Once the webcam is inactive, it restores your default wallpaper.


What We’ll Cover

  1. Monitoring Webcam Activity: Using Windows Registry to detect active webcam applications.
  2. Changing Wallpaper Programmatically: Leveraging Python’s ctypes to update the desktop wallpaper.
  3. Automating the Process: Running the script in the background for seamless automation.

Prerequisites

Before diving into the script, make sure you have the following:

  1. Python 3 installed on your system.
  2. Basic familiarity with running Python scripts.
  3. Two wallpaper images:
    • A bright white image (white_wallpaper.png).
    • Your default wallpaper (default_wallpaper.png).

The Python Script

Below is the full Python script:

import time
import os
import ctypes
import winreg

WHITE_WALLPAPER_PATH = r"C:\Users\username\Pictures\white_wallpaper.jpg"
DEFAULT_WALLPAPER_PATH = r"C:\Users\grego\Pictures\backgrounds\original_background.jpg"

def set_wallpaper(image_path):
    """Change the desktop wallpaper."""
    ctypes.windll.user32.SystemParametersInfoW(20, 0, image_path, 0)


class WebcamDetect:
    REG_KEY = winreg.HKEY_CURRENT_USER
    WEBCAM_REG_SUBKEY = r"SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\webcam"
    WEBCAM_TIMESTAMP_VALUE_NAME = "LastUsedTimeStop"

    def __init__(self):
        pass

    def get_active_apps(self):
        """Returns a list of apps that are currently using the webcam."""
        def get_subkey_timestamp(subkey) -> int:
            """Returns the timestamp of the subkey."""
            try:
                value, _ = winreg.QueryValueEx(subkey, WebcamDetect.WEBCAM_TIMESTAMP_VALUE_NAME)
                return value
            except OSError:
                return None

        active_apps = []
        try:
            key = winreg.OpenKey(WebcamDetect.REG_KEY, WebcamDetect.WEBCAM_REG_SUBKEY)
            subkey_count, _, _ = winreg.QueryInfoKey(key)

            for idx in range(subkey_count):
                subkey_name = winreg.EnumKey(key, idx)
                subkey_path = f"{WebcamDetect.WEBCAM_REG_SUBKEY}\\{subkey_name}"
                subkey = winreg.OpenKey(WebcamDetect.REG_KEY, subkey_path)

                if subkey_name == "NonPackaged":
                    np_subkey_count, _, _ = winreg.QueryInfoKey(subkey)
                    for np_idx in range(np_subkey_count):
                        np_subkey_name = winreg.EnumKey(subkey, np_idx)
                        np_subkey_path = f"{WebcamDetect.WEBCAM_REG_SUBKEY}\\NonPackaged\\{np_subkey_name}"
                        np_subkey = winreg.OpenKey(WebcamDetect.REG_KEY, np_subkey_path)
                        if get_subkey_timestamp(np_subkey) == 0:
                            active_apps.append(np_subkey_name)
                        winreg.CloseKey(np_subkey)
                else:
                    if get_subkey_timestamp(subkey) == 0:
                        active_apps.append(subkey_name)

                winreg.CloseKey(subkey)
            winreg.CloseKey(key)
        except OSError as e:
            print(f"Error accessing registry: {e}")
        return active_apps

    def is_active(self):
        """Returns True if the webcam is active, False otherwise."""
        return len(self.get_active_apps()) > 0


if __name__ == "__main__":
    print("Starting webcam monitor...")
    detector = WebcamDetect()
    webcam_was_active = False

    while True:
        try:
            if detector.is_active():
                if not webcam_was_active:
                    print("Webcam activated. Changing wallpaper to white.")
                    set_wallpaper(WHITE_WALLPAPER_PATH)
                    webcam_was_active = True
            else:
                if webcam_was_active:
                    print("Webcam deactivated. Restoring default wallpaper.")
                    set_wallpaper(DEFAULT_WALLPAPER_PATH)
                    webcam_was_active = False
        except Exception as e:
            print(f"An error occurred: {e}")

        time.sleep(1)

How It Works

###Webcam Activity Detection:

The script reads the Windows Registry to find applications using the webcam.

It checks the LastUsedTimeStop value; if it’s 0, the webcam is active.

Changing the Wallpaper:

The set_wallpaper function uses the SystemParametersInfoW function from ctypes to update the desktop wallpaper.

Monitoring in Real Time:

The script runs an infinite loop, checking the webcam status every second and adjusting the wallpaper accordingly.

Setting Up the Script

Prepare Your Wallpapers:

Save a white image as white_wallpaper.png.

Save your default wallpaper as default_wallpaper.png.

Update the file paths in the script.

Install Python:

If Python is not installed, download and install it.

Run the Script:

Save the script as webcam_wallpaper.py.

Run it from the terminal (command prompt on Windows):

python webcam_wallpaper.py

Automate on Startup (Optional):

Convert the script to an executable using PyInstaller:

pip install pyinstaller
pyinstaller --onefile webcam_wallpaper.py

Place the executable in your startup folder (shell:startup in the Run dialog).

Conclusion

With this script, your monitor becomes a handy light source whenever your webcam is in use. It’s a simple yet effective way to enhance your webcam experience for video calls or recordings.