0

I am trying to get the process name of the currently focused window with python. Right now I am working with this:

import pygetwindow as gw
print(gw.getActiveWindow().title)

The problem is that this only prints the name of the active window which is not really helpful, because sometimes the title of the application does not help at all to get it's process name (Spotify for example displays the current track and song name instead of "Spotify").

pygetwindow has a lot of options but I don't know if there is another library that would give me the desired output of the process' name.

Thanks in advance.

Adnan Taufique
  • 379
  • 1
  • 9
Luca Tatas
  • 160
  • 1
  • 14
  • 1
    Does this answer your question? [win32gui get the current active application name](https://stackoverflow.com/questions/14394513/win32gui-get-the-current-active-application-name) – CrazyChucky Dec 18 '20 at 19:31
  • Honestly no! win32gui has not been updated for over 3 years now, so I don't want to use it. – Luca Tatas Dec 18 '20 at 19:33
  • 1
    Well unfortunately it seems `pygetwindow` has the opposite problem. It's still in development, and looking through the code, I don't see any obvious way to get the process or application name. – CrazyChucky Dec 18 '20 at 19:34
  • Hm okay, maybe I have to go with win32gui - for now. Thanks! – Luca Tatas Dec 18 '20 at 19:36
  • 1
    I've not used it and am not sure if it would do what you want, but you might want to check out [Python/WinRT](https://pypi.org/project/winrt/). (And if you figure out how to do it (before someone else answers), don't forget to come back and answer your own question so others can find it!) – CrazyChucky Dec 18 '20 at 19:41

1 Answers1

2

This worked for me: I modified the code of this post: Similar question

import win32gui, win32process, psutil

def active_window_process_name():
    try:
        pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())
        return(psutil.Process(pid[-1]).name())
    except:
        pass

print(active_window_process_name())
Luca Tatas
  • 160
  • 1
  • 14