使用Python获取其他正在运行的进程窗口大小

问题描述 投票:8回答:4

这听起来不像是恶意的,我想获取它们当前的窗口大小,而不是看看它们中的内容。目的是弄清楚如果其他所有窗口都全屏显示,那么我也应该这样启动。或者,尽管分辨率很高,但所有其他进程的分辨率仅为800x600,那么这可能正是用户想要的。为什么要让他们浪费时间和精力来调整我的窗口的大小以匹配他们拥有的所有其他窗口?我主要是Windows devoloper,但如果有跨平台的方法,至少不会让我感到不安。

python windows winapi pywin32
4个回答
12
投票

使用WindowMover articleNattee Niparnan's blog post的提示,我设法创建了此提示:

import win32con
import win32gui

def isRealWindow(hWnd):
    '''Return True iff given window is a real Windows application window.'''
    if not win32gui.IsWindowVisible(hWnd):
        return False
    if win32gui.GetParent(hWnd) != 0:
        return False
    hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0
    lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)
    if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)
      or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):
        if win32gui.GetWindowText(hWnd):
            return True
    return False

def getWindowSizes():
    '''
    Return a list of tuples (handler, (width, height)) for each real window.
    '''
    def callback(hWnd, windows):
        if not isRealWindow(hWnd):
            return
        rect = win32gui.GetWindowRect(hWnd)
        windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1])))
    windows = []
    win32gui.EnumWindows(callback, windows)
    return windows

for win in getWindowSizes():
    print win

您需要Win32 Extensions for Python module才能正常工作。

编辑:我发现GetWindowRectGetClientRect给出更正确的结果。来源已更新。


9
投票

我是AutoIt的忠实拥护者。它们具有COM版本,可让您使用Python的大多数功能。

import win32com.client
oAutoItX = win32com.client.Dispatch( "AutoItX3.Control" )

oAutoItX.Opt("WinTitleMatchMode", 2) #Match text anywhere in a window title

width = oAutoItX.WinGetClientSizeWidth("Firefox")
height = oAutoItX.WinGetClientSizeHeight("Firefox")

print width, height

2
投票

检查Windows的Python扩展中的win32gui module。它可能提供您正在寻找的某些功能。


0
投票

我更新了GREAT @DZinX代码,添加了窗口的标题/文本:

win32gui
© www.soinside.com 2019 - 2024. All rights reserved.