ick*_*fay 26
假设你使用的是Windows,请尝试使用pywin32的win32gui模块,它EnumWindows和GetWindowRect功能.
如果您使用的是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()
Run Code Online (Sandbox Code Playgroud)
Gre*_*ill 10
您可以使用该GetWindowRect功能获取窗口坐标.为此,您需要一个窗口句柄,您可以使用它FindWindow,假设您知道窗口的某些内容(例如标题).
要从Python调用Win32 API函数,请使用pywin32.
小智 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)
Run Code Online (Sandbox Code Playgroud)
供将来参考:PyWin32GUI 现已移至 Github
这可以从窗口标题返回窗口矩形
import ctypes
from ctypes.wintypes import HWND, DWORD, RECT
def GetWindowRectFromName(name:str)-> tuple:
hwnd = ctypes.windll.user32.FindWindowW(0, name)
rect = ctypes.wintypes.RECT()
ctypes.windll.user32.GetWindowRect(hwnd, ctypes.pointer(rect))
# print(hwnd)
# print(rect)
return (rect.left, rect.top, rect.right, rect.bottom)
if __name__ == "__main__":
print(GetWindowRectFromName('CALC'))
pass
Run Code Online (Sandbox Code Playgroud)
Python 3.8.2 | 由 conda-forge 打包 | (默认,2020 年 4 月 24 日,07:34:03)[MSC v.1916 64 位 (AMD64)] 在 win32 Windows 10 Pro 1909 上