python --Open the window according to the windows window name and process pid (pygetwindow detailed explanation)

Detailed explanation of pygetwindow

Introduction:
pygetwindow It is a Python library for obtaining, manipulating and managing the currently open windows. It provides some common window operation methods, including getting window handle, getting window position and size, moving and resizing windows, minimizing, maximizing and restoring windows, and simulating input and focus control, etc.

Install

pip install pygetwindow==0.0.9

Detailed explanation

Get all current windows

import pygetwindow as gw

# 获取当前所有窗口
windows = gw.getAllWindows()
for window in windows:
print(window)

Get the window with the specified title

import pygetwindow as gw

# 获取指定标题的窗口
title = "计算器"
window = gw.getWindowsWithTitle(title)[0]
print(window)

Get window position and size

import pygetwindow as gw

# 获取窗口位置和大小
title = "计算器"
window = gw.getWindowsWithTitle(title)[0]
print(window.left, window.top, window.width, window.height)

Moving and resizing windows

import pygetwindow as gw

# 移动和调整窗口大小
title = "计算器"
window = gw.getWindowsWithTitle(title)[0]
window.moveTo(0, 0)
window.resizeTo(800, 600)

Minimize, maximize and restore windows

import pygetwindow as gw

# 最小化、最大化和还原窗口
title = "计算器"
window = gw.getWindowsWithTitle(title)[0]
# 最小化窗口
window.minimize()
# 最大化窗口
window.maximize()
# 还原窗口
window.restore()

Simulate keyboard input and mouse clicks

import pygetwindow as gw
import time

# 模拟键盘输入和鼠标点击
title = "计算器"
window = gw.getWindowsWithTitle(title)[0]
window.activate() # 激活窗口,使得键盘输入和鼠标操作生效
window.type("123+456=") # 模拟键盘输入
time.sleep(1) # 等待1秒
window.mouseClick(button="left", x=50, y=50) # 模拟鼠标左键单击

search window

You can use findTopWindow()the method to find the top-level window based on the class name or window title, or you can use getWindows()the method to get all windows and traverse to find a specific window.

import pygetwindow as gw

Find top-level windows based on their window titles

window = gw.findTopWindow(title='My Window')

Iterate through all windows to find a specific window

for window in gw.getWindows():
	if 'My Window' in window.title:
		print(window.title)

Sending keyboard and mouse events
You can use the keydown()method keyup()to send key events, use click()the method to send mouse click events, and use dragTo()the method to send mouse drag events.

# 根据窗口标题获取窗口对象
window = gw.getWindowsWithTitle('My Window')[0]

# 发送按键事件
window.keyDown('ctrl')
window.keyDown('alt')
window.keyUp('ctrl')
window.keyUp('alt')

# 发送鼠标单击事件
window.click()

# 发送鼠标拖动事件
window.dragTo(500, 500)

window on top

You can use setAlwaysOnTop()the method to bring the window to the top.

import pygetwindow as gw

# 根据窗口标题获取窗口对象
window = gw.getWindowsWithTitle('My Window')[0]

# 将窗口置顶
window.setAlwaysOnTop(True)

open window by window name

import win32con
import win32gui
import win32print


def get_real_resolution():
    """获取真实的分辨率"""
    hdc = win32gui.GetDC(0)
    return win32print.GetDeviceCaps(hdc, win32con.DESKTOPHORZRES), \
           win32print.GetDeviceCaps(hdc, win32con.DESKTOPVERTRES)


window_hwnd: list = []
win32gui.EnumWindows(lambda _hwd, param: param.append(_hwd), window_hwnd)
status = False
for hwd in window_hwnd:
    if win32gui.GetWindowText(hwd) == 'MAX BOX 3.1.5':
        import pygetwindow
        width, height = get_real_resolution()
        print(f'激活窗口:{width};{height}')

        window = pygetwindow.getWindowsWithTitle(f"MAX BOX 3.1.5")[0]
        window.activate()

        # win32gui.ShowWindow(hwd, win32con.SW_MAXIMIZE)
        # win32gui.MoveWindow(hwd, (width - 1750) // 2, (height - 850) // 2, 1750, 850, True)
        # status = True
        break

Open window according to process pid

method one

import win32gui
import win32process

pid = 1234 # 替换成你要打开的进程的PID

# 获取指定进程的主窗口句柄
hwnd = win32gui.FindWindow(None, f"PID:{pid}")

# 获取该进程的线程ID和进程ID
tid, procid = win32process.GetWindowThreadProcessId(hwnd)

# 将该窗口设为前台窗口(激活窗口)
win32gui.SetForegroundWindow(hwnd)

It should be noted that this method is only applicable to Windows systems, and it also needs to run the program with administrator privileges. Also, if the process has multiple windows, you may need to FindWindow()specify more precise window title or class name parameters in the method to ensure that the correct window is found.

Method Two

import pygetwindow

pid = 1234 # 替换成你要打开的进程的PID

# 找到指定PID的窗口
window = pygetwindow.getWindowsWithTitle(f"PID: {
      
      pid}")[0]

# 激活窗口
window.activate()

The getWindowsWithTitle()parameters of the method can be the title of the window, the process ID, and so on. In the above example, we used "PID: {pid}"to find the window of the specified process. If multiple eligible windows are found, you can use the subscript to select the window that needs to be operated.

It should be noted that this method can only be used under the Windows system, and the program needs to be run with administrator privileges.

Guess you like

Origin blog.csdn.net/weixin_44634704/article/details/129861909