# Function to monitor active window
def monitor_active_window():
last_window = ""
while True:
try:
hwnd = win32gui.GetForegroundWindow()
_, pid = win32process.GetWindowThreadProcessId(hwnd)
process = psutil.Process(pid)
window_title = process.name()
if window_title != last_window:
last_window = window_title
print(f"Window change detected: {window_title}")
screenshot_path = take_screenshot()
send_email("Tab Change Alert", f"A tab/window change was detected: {window_title}", screenshot_path)
os.remove(screenshot_path)
except Exception as e:
print(f"Error monitoring active window: {e}")
time.sleep(1)
Explanation :
This monitor_active_window function continuously monitors the currently active window on the system, detects when it changes, and takes specific actions such as sending an email alert and taking a screenshot. Here’s how it works:
Functionality
Track Last Window:
last_window = "": Initializes a variable to store the title of the previously active window. This helps detect changes.
Monitor Active Window in a Loop:
The while True loop continually checks for the currently active window.
Get Active Window:
win32gui.GetForegroundWindow(): Retrieves the handle of the currently active (foreground) window.
win32process.GetWindowThreadProcessId(hwnd): Gets the process ID (pid) of the process associated with the active window.
psutil.Process(pid): Retrieves details of the process using the PID.
Detect Window Changes:
window_title = process.name(): Retrieves the name of the process owning the active window.
If the active window name (window_title) differs from the last_window, it indicates a change.
Take Action on Change:
Updates last_window to the new window's title.
Logs the change with print(f"Window change detected: {window_title}").
Takes a screenshot using the take_screenshot() function.
Sends an email alert via the send_email() function, including the window title in the message and attaching the screenshot.
Deletes the screenshot file using os.remove(screenshot_path) to save disk space.
Error Handling:
Catches exceptions (e.g., missing permissions or window focus issues) and logs the error. The program continues running after a brief pause.
Pause Between Checks:
time.sleep(1): Introduces a 1-second delay between checks to reduce CPU usage.