I try to find the path to executable of the current active window in python. I am not familiar with system variables and did not know what i should do and i found a few solutions and practicing with them .
First i try to get current active window and finding the related PID and then the path.
import psutil
import win32process
import win32gui
window = win32gui.GetForegroundWindow()
pid = win32process.GetWindowThreadProcessId(window)
active_window_path = psutil.Process(pid[1]).exe()
print("Active window: %s" % str(get_active_window()))
While i get PID with win32process it returns a list .Why ? I had to select 1st element of the list to get the correct result . isn't PID should be a integer ? Why it is returning a list ? And why 2nd element is correct and not first ?
It's part of [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions, which is a Python wrapper over WINAPIs.
[GitHub.MHammond]: win32process.GetWindowThreadProcessId wraps [MS.Learn]: GetWindowThreadProcessId function (winuser.h)
Returns a tuple consisting of 2 ints:
Thread ID (TId)
Process ID (PId)
Change (the relevant parts of) your code (not mandatory, just for readability) to:
import win32process as wproc
# ...
tid, pid = wproc.GetWindowThreadProcessId(window)
active_window_path = psutil.Process(pid).exe()