查找应用程序的宽度和高度 - 跨平台

-1 投票
1 回答
577 浏览
提问于 2025-04-17 11:01

我想找一种方法来获取指定窗口的尺寸(宽度和高度)。到目前为止,我一直在使用AutoIt的功能,只需写出窗口或框架名称的一部分,它就能像我想要的那样工作。唯一的问题是,这个方法只在微软的Windows系统上有效。我希望它能在不同的平台上都能使用(包括Windows和Linux)。

由于这两个平台差别很大,所以需要写两个脚本,一个用于Windows,另一个用于Linux。而且我希望不依赖额外的程序(比如AutoIt)。我不想在脚本中“硬编码”要选择哪个框架。我希望它能像AutoIt那样,通过指定框架的名称或其部分内容来工作。

1 个回答

1

我找到了在Windows上怎么做这个的方法,感谢yurib的帮助。

import win32con
import win32gui

def inText(haystack, needle, n):
    parts= haystack.split(needle, n+1)
    if len(parts)<=n+1:
        return False
    if len(haystack)-len(parts[-1])-len(needle):
        return True

def isRealWindow(hWnd):
    '''Return True if 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(text):
    '''Return a list of tuples (handler, (width, height)) for each real window.'''
    def callback(hWnd, extra):
        if not isRealWindow(hWnd):
            return
        title   = win32gui.GetWindowText(hWnd)
        rect    = win32gui.GetWindowRect(hWnd)
        isFrame = inText(title, text, 0)
        if(isFrame):
            windows.append((title, rect[2] - rect[0], rect[3] - rect[1], rect[0],rect[1]))
    windows = []
    win32gui.EnumWindows(callback, windows)
    return windows

def findWindow(text):
    window = getWindowSizes(text)
    name = window[0][0]
    w = window[0][1]
    h = window[0][2]
    x = window[0][3]
    y = window[0][4]

    return name,w,h,x,y

现在我想知道在Linux上怎么做类似的事情……有没有什么提示?

撰写回答