Python gets and sets the Current Windows window

Time:2021-9-15

In the process of screen automation in Python, it is inevitable to involve the operation of windows. Theoretically, it can be realized with mouse and keyboard + screen recognition (complete simulation of people), but it is a little troublesome to do it. If cross platform compatibility is not considered, the introduction of Win32 GUI library can save a lot of things.

Get current window

import win32gui
#Get window handle
hwnd = win32gui.GetForegroundWindow()
#Get window title
win32gui.GetWindowText(hwnd)

Find window

import win32gui
#Find window by title
Title = 'document'
hwnd = win32gui.FindWindow(None, title)

Set current window

import win32gui
#According to handle
HWnd = 5378992 # handle should be obtained by other methods
win32gui.SetForegroundWindow(hwnd)

Complete example

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__":
    #Gets the current window handle (which is an integer)
    print(get_current_window())
    #Gets the title of the current window
    print(get_current_window_title())

    #Given a title, find this window, and if you find it, put it at the top
    hwnd = find_ window_ by_ Title ('Document ')
    set_current_window(hwnd)
    time.sleep(1)
    #Print the title of the window just switched to the front
    print(get_current_window_title())