How to check if there are any active windows open in Python?

1.1k Views Asked by At

I'm trying to write a Python script where I try to check if any application, besides the current one, is active. If there are any other open windows, I want a pop up question that asks me if I want to close the running applications.

I now found the way to find active processes like this:

import win32gui

def winEnumHandler( hwnd, ctx ):
    if win32gui.IsWindowVisible( hwnd ):
        print (hex(hwnd), win32gui.GetWindowText( hwnd ))

win32gui.EnumWindows( winEnumHandler, None )

The problem is, this returns only the title names of the active window. But I need the process names to close these windows and somehow I cannot get them.

Does anybody have an idea on how to solve this?

1

There are 1 best solutions below

0
On

If python process running you can see process named python.exe

here is a script to terminate desired process by name :

import psutil
import os


# Iterate over all running process
def running_procs():
    for proc in psutil.process_iter():
        try:
            # Get process name & pid from process object.
            processName = proc.name()
            processID = proc.pid
            print(processName , ' ::: ', processID)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass

def kill_proc(proc):
    os.system(f"taskkill /im {proc}.exe /f")