获取窗口位置& python的大小

时间:2011-08-22 01:24:52

标签: python windows

如何使用python获取和设置窗口(任何Windows程序)的位置和大小?

7 个答案:

答案 0 :(得分:26)

假设您使用的是Windows,请尝试使用pywin32的{​​{1}}模块及其win32guiEnumWindows个功能。

如果您使用的是Mac OS X,则可以尝试使用GetWindowRect

对于Linux,您可以尝试使用X11的许多接口之一。

编辑:Windows示例(未测试):

appscript

答案 1 :(得分:7)

您可以使用GetWindowRect功能获取窗口坐标。为此,您需要一个窗口句柄,您可以使用FindWindow获取该句柄,假设您对窗口有所了解(例如标题)。

要从Python调用Win32 API函数,请使用pywin32

答案 2 :(得分:2)

对于Linux,您可以使用我制作的工具here。该工具的用途略有不同,但您可以直接使用API​​来满足您的需求。

安装工具

sudo apt-get install xdotool xprop xwininfo
git clone https://github.com/Pithikos/winlaunch.git && cd winlaunch

在终端

>>> from winlaunch import *
>>> wid, pid = launch('firefox')
>>> win_pos(wid)
[3210, 726]

widpid分别代表窗口ID和进程ID。

答案 3 :(得分:2)

这可以从窗口标题返回窗口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

环境

Python 3.8.2 |由conda-forge打包| (默认值,2020年4月24日,07:34:03)在Win32上的[MSC v.1916 64位(AMD64)] Windows 10专业版1909

答案 4 :(得分:1)

正如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

答案 5 :(得分:0)

此代码将在Windows上运行。它返回活动窗口的位置和大小。

from win32gui import GetWindowText, GetForegroundWindow
print(win32gui.GetWindowRect(GetForegroundWindow()))

答案 6 :(得分:0)

在任何其他回复中都没有提到的是,在较新的 Windows(Vista 及更高版本)中,“the Window Rect now includes the area occupied by the drop shadow.”是 win32gui.GetWindowRectctypes.windll.user32.GetWindowRect 所连接的接口。< /p>

如果您想获得没有阴影的位置和大小,您可以:

  1. 手动删除它们。就我而言,左侧、底部和右侧有 10 个像素必须修剪。
  2. 使用 dwmapi 提取文章中提到的 DWMWA_EXTENDED_FRAME_BOUNDS

关于使用 dwmapi.DwmGetWindowAttribute(参见 here):

这个函数有四个参数:hwnd,我们感兴趣的属性的标识符,写入属性的数据结构的指针,这个数据结构的大小。我们通过检查 this enum 获得的标识符。在我们的例子中,属性 DWMWA_EXTENDED_FRAME_BOUNDS 位于位置 9。

import ctypes
from ctypes.wintypes import HWND, DWORD, RECT

dwmapi = ctypes.WinDLL("dwmapi")

hwnd = 133116    # refer to the other answers on how to find the hwnd of your window

rect = RECT()
DMWA_EXTENDED_FRAME_BOUNDS = 9
dwmapi.DwmGetWindowAttribute(HWND(hwnd), DWORD(DMWA_EXTENDED_FRAME_BOUNDS),
                             ctypes.byref(rect), ctypes.sizeof(rect))

print(rect.left, rect.top, rect.right, rect.bottom)

最后:“请注意,与 Window Rect 不同,DWM Extended Frame Bounds 未针对 DPI 进行调整”。

相关问题