I've done something similar to this before for a Python overlay I've made, and extracted the code to this:
import win32gui # Import the windows API for getting open apps
apps = [] # Leave blank as the getWindows() function will autofill this in
ignoredApps = ['ABC'] # Any apps you want to exclude (such as built-in apps or extra windows such as paint.net windows) go here, or leave the list empty
def getWindows(hwnd, *args)->list: # This returns always returns a list, and it takes in a hwnd argument and multiple other arguments to be ignored.
global apps
if win32gui.IsWindowVisible( hwnd ):
title = win32gui.GetWindowText( hwnd ) # Gets title
if not title == '': # To ensure the title of the program is not blank
if not title in apps and not title in ignoredApps: # Prevent duplicate app listings and listing ignored apps
apps.append(title) # Append to public apps variable, you can do other stuff with the title variable such as only get the content after the last dash symbol as I did for my overlay
win32gui.EnumWindows( getWindows, '' ) # Call the function with hwnd argument filled
print(apps) # Print the list of open apps, excluding any apps in ignoredApps
The list appears to be sorted from most recently focused/opened. Example: If you just focused on Google Chrome, then Google Chrome will be at the top of the list. If you focus/open another application then said application will be at the top.
Make sure that you have the pywin32
module installed, otherwise you will get a ModuleNotFoundError: No module named 'win32gui'
exception. You can directly install it via pip install pywin32
. I tested this using pywin32==303
as listed by pip freeze
which shows all installed PIP modules.