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

2024-05-21 01:44:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这不像听起来那么恶意,我想知道他们的窗口的当前大小,而不是看看里面是什么。目的是找出如果其他窗口都是全屏的,那么我也应该这样启动。或者,如果所有其他进程都只有800x600,尽管有一个巨大的分辨率,那么这可能是用户想要的。为什么要让他们浪费时间和精力调整我的窗口以匹配他们所有的其他窗口?我主要是一个Windows开发人员,但如果有一个跨平台的方法来做这件事,我一点也不难过。


Tags: 方法用户目的进程开发人员windows跨平台分辨率
3条回答

我是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

查看Python的Windows扩展中的^{} module。它可能提供一些您正在寻找的功能。

使用来自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给出的结果更正确。已更新源。

相关问题 更多 >