Skip to content

Instantly share code, notes, and snippets.

@cobryan05
Last active April 22, 2024 11:40
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cobryan05/8e191ae63976224a0129a8c8f376adc6 to your computer and use it in GitHub Desktop.
Save cobryan05/8e191ae63976224a0129a8c8f376adc6 to your computer and use it in GitHub Desktop.
Query registry for active webcam
# 2024-04-17: Stole changese from @Timmo on stackoverflow to get this working with Windows Apps
import winreg
class WebcamDetect:
REG_KEY = winreg.HKEY_CURRENT_USER
WEBCAM_REG_SUBKEY = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\CapabilityAccessManager\\ConsentStore\\webcam\\"
WEBCAM_TIMESTAMP_VALUE_NAME = "LastUsedTimeStop"
def __init__(self):
self._regKey = winreg.OpenKey( WebcamDetect.REG_KEY, WebcamDetect.WEBCAM_REG_SUBKEY )
def getActiveApps(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:
pass
return None
active_apps = []
try:
key = winreg.OpenKey(WebcamDetect.REG_KEY, WebcamDetect.WEBCAM_REG_SUBKEY)
# Enumerate over the subkeys of the webcam key
subkey_count, _, _ = winreg.QueryInfoKey(key)
# Recursively open each subkey and check the "LastUsedTimeStop" value.
# A value of 0 means the camera is currently in use.
for idx in range(subkey_count):
subkey_name = winreg.EnumKey(key, idx)
subkey_name_full = f"{WebcamDetect.WEBCAM_REG_SUBKEY}\\{subkey_name}"
subkey = winreg.OpenKey(WebcamDetect.REG_KEY, subkey_name_full)
if subkey_name == "NonPackaged":
# Enumerate over the subkeys of the "NonPackaged" key
subkey_count, _, _ = winreg.QueryInfoKey(subkey)
for np_idx in range(subkey_count):
subkey_name_np = winreg.EnumKey(subkey, np_idx)
subkey_name_full_np = f"{WebcamDetect.WEBCAM_REG_SUBKEY}\\NonPackaged\\{subkey_name_np}"
subkey_np = winreg.OpenKey(WebcamDetect.REG_KEY, subkey_name_full_np)
if get_subkey_timestamp(subkey_np) == 0:
active_apps.append(subkey_name_np)
else:
if get_subkey_timestamp(subkey) == 0:
active_apps.append(subkey_name)
winreg.CloseKey(subkey)
winreg.CloseKey(key)
except OSError:
pass
return active_apps
def isActive(self):
return len(self.getActiveApps()) > 0
@probablypablito
Copy link

Thank you so much! This seems to be literally the only way to get camera status. Sucks that there isn't a better way

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment