使用Python获取窗口位置和大小

44 投票
8 回答
103790 浏览
提问于 2025-04-17 00:04

我怎么用Python获取和设置窗口(任何Windows程序)的位置信息和大小呢?

8 个回答

9

正如Greg Hewgill提到的,如果你知道窗口的名字,你可以直接使用win32gui里的FindWindow和GetWindowRect。这种方法可能比之前的方法更简洁和高效。

from win32gui import FindWindow, GetWindowRect

# FindWindow takes the Window Class name (can be None if unknown), and the window's display text. 
window_handle = FindWindow(None, "Diablo II")
window_rect   = GetWindowRect(window_handle)

print(window_rect)
#(0, 0, 800, 600)

供以后参考:PyWin32GUI现在已经转移到Github上了

16

你可以通过 GetWindowRect 这个函数来获取窗口的坐标。为了使用这个函数,你需要一个窗口的句柄,也就是窗口的唯一标识。你可以通过 FindWindow 函数来获取这个句柄,前提是你对这个窗口有一些了解,比如它的标题。

如果你想在 Python 中调用 Win32 API 函数,可以使用 pywin32 这个库。

48

假设你在使用Windows系统,可以试试用pywin32里的win32gui模块,里面有EnumWindowsGetWindowRect这两个功能。

如果你是在Mac OS X上,可以尝试使用appscript

在Linux系统上,你可以试试很多与X11相关的接口。

编辑:这是一个Windows的例子(未测试):

import win32gui

def callback(hwnd, extra):
    rect = win32gui.GetWindowRect(hwnd)
    x = rect[0]
    y = rect[1]
    w = rect[2] - x
    h = rect[3] - y
    print("Window %s:" % win32gui.GetWindowText(hwnd))
    print("\tLocation: (%d, %d)" % (x, y))
    print("\t    Size: (%d, %d)" % (w, h))

def main():
    win32gui.EnumWindows(callback, None)

if __name__ == '__main__':
    main()

撰写回答