Search code examples
pythonpyautogui

How to get the names of the windows that are open and switch to a target window?


I have been searching everywhere on how to do this specifically but to no avail.

Let's say I want to get a list of all the open windows/apps on my device: Open apps

The next thing I want to do is to search for a window with a name "Notepad", or maybe "Facebook", then switch and maximize those window as the main window on the screen.

I've been using pyautogui module for switching tabs by automatically pressing alt + tab keys with the module. However, I believe it'll be prone to mistakes if I have no way of checking which tab/window is currently selected or maximized.

I was thinking of a solution that I can just continuously automate pressing alt + tab until the target window name is in the current active window, but I don't know how to get the name of the current active window as well.

Thank you for the help in advance.


Solution

  • I just found out that pyautogui has a method to get the active window title as well.

    import pyautogui
    import time
    
    target_window = 'notepad'
    count = 0
    
    while True:
        window_title = pyautogui.getActiveWindowTitle()
    
        if target_window not in window_title:
            count += 1
            with pyautogui.hold('alt'):
                for _ in range(0, count):
                     pyautogui.press('tab')
    
         time.sleep(0.25)