In the process of Python screen automation, it is inevitable to involve the operation of the window. Theoretically, you can use mouse and keyboard + screen recognition (complete simulation of people) to achieve this, but it is a bit troublesome to do it in detail. If you don’t consider cross-platform compatibility, then the introduction of Win32GUI library, can save a lot of work.

Get the current window

Import win32gui # access to handle to the window HWND. = win32gui GetForegroundWindow (#) to obtain the window title win32gui. GetWindowText (HWND)

To find the window

Hwnd = Win32Gui.FindWindow(None, title)

Set the current window

The import win32gui # according to the HWND = 5378992 # handle handle should be the other way to get to the win32gui. The SetForegroundWindow (HWND)

Complete sample

import time import win32gui def get_current_window(): return win32gui.GetForegroundWindow() def set_current_window(hwnd): win32gui.SetForegroundWindow(hwnd) def get_window_title(hwnd): return win32gui.GetWindowText(hwnd) def get_current_window_title(): return get_window_title(get_current_window()) def find_window_by_title(title): try: return win32gui.FindWindow(None, title) except Exception as ex: print('error calling win32gui.FindWindow ' + str(ex)) return -1 if __name__ == "__main__": Print (get_current_window()) print(get_current_window_title()) print(get_current_window_title()) print(get_current_window_title()) HWND = find_window_by_title(' document ') set_current_window(HWND) time.sleep(1) # Print the title of the window that has just been switched to the front print(get_current_window_title())