Skip to content

Instantly share code, notes, and snippets.

@Gipetto
Last active September 24, 2025 22:00
Show Gist options
  • Select an option

  • Save Gipetto/cbedfec15f60d6560593a8d75e7192c7 to your computer and use it in GitHub Desktop.

Select an option

Save Gipetto/cbedfec15f60d6560593a8d75e7192c7 to your computer and use it in GitHub Desktop.
Monitor MacOS for focus state changes.
#!/usr/bin/env python3
# Detect when window focus changes
#
# Tested with MacOS Sequoia 15.7
#
# Install requirements:
# pip3 install pyobjc-core pyobjc-framework-Cocoa
from AppKit import NSWorkspace
import time
import datetime
last = None
while True:
time.sleep(1)
activeApplication = NSWorkspace.sharedWorkspace().activeApplication()
if not activeApplication:
continue
current = activeApplication["NSApplicationBundleIdentifier"]
# if last != current and currentId == "com.your.suspect.application.domain":
if last != current:
print(
f"[{datetime.datetime.now()}] Focus changed to {activeApplication["NSApplicationName"]} ({current}) at {activeApplication["NSApplicationPath"]}")
last = current
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment