Switch Windows Screen with Python

Asked

Viewed 321 times

0

Good Afternoon!

Guys, I’m writing a Python script using the Pyautogui library. At some point, this script "needs to navigate between screens", example, my script is working a report within my TMS system and needs to go to certain Excel screen. How could I make my script always seven the correct screen?

Remembering, I can already get the PID of the program, using the library Psutil.

  • there is the Pygetwindow module

1 answer

1

To activate a out of focus or minimized window, I usually use the function below.

The 'win_name' argument must be the name of the process/window to maximize.

def win_act(win_name):
    import win32gui
    import re

    class WindowMgr:
        """Encapsulates some calls to the winapi for window management"""

        def __init__(self):
            """Constructor"""
            self._handle = None

        def find_window(self, class_name, window_name=None):
            """find a window by its class_name"""
            self._handle = win32gui.FindWindow(class_name, window_name)

        def _window_enum_callback(self, hwnd, wildcard):
            """Pass to win32gui.EnumWindows() to check all the opened windows"""
            if re.match(wildcard,
                         str(win32gui.GetWindowText(hwnd))) is not None:
                self._handle = hwnd

        def find_window_wildcard(self, wildcard):
            """find a window whose title matches the wildcard regex"""
            self._handle = None
            win32gui.EnumWindows(self._window_enum_callback, wildcard)

        def set_foreground(self):
            """put the window in the foreground"""
            win32gui.SetForegroundWindow(self._handle)

    w = WindowMgr()
    for x in range(3):
        w.find_window_wildcard(f".*{win_name}*")
        w.set_foreground()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.