获取其他运行进程的窗口大小(Python)
这听起来可能有点可怕,但其实我只是想知道他们窗口的当前大小,而不是查看里面的内容。我的目的是想搞清楚,如果其他窗口都是全屏的,那我也应该以全屏的方式启动。或者如果其他程序的窗口都是800x600的大小,尽管屏幕分辨率很高,那可能就是用户想要的。为什么要让他们浪费时间和精力去调整我的窗口大小,让它和其他窗口一致呢?我主要是做Windows开发的,但如果有一种跨平台的方法来实现这个功能,我也不会介意。
5 个回答
2
你可以看看这个win32gui
模块,这是Python在Windows上的一个扩展。它可能会提供你需要的一些功能。
10
我非常喜欢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
13
根据WindowMover文章和Nattee Niparnan的博客中的一些提示,我成功创建了这个:
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
要让这个工作,你需要安装Python的Win32扩展模块。
补充说明:我发现GetWindowRect
的结果比GetClientRect
更准确。源代码已经更新。