使用缩放监视器捕获Python应用程序



我正在尝试捕获一个窗口(在示例代码中,我将使用firefox(,我正在运行两个监视器,第一个监视器在2736x1824中,具有200%的缩放比例,第二个监视器在1920x1080中,具有100%的缩放比例。

from win32 import win32gui
def enum_cb(hwnd, results):
# CallBack function for enumeration
winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
def get_screens():
win32gui.EnumWindows(enum_cb, winlist)
return [(hwnd, title) for hwnd, title in winlist if title]
def get_screensbyname(screen_name):
# Function who gets a screen by name
winlist = get_screens()
screens = [(hwnd, title) for hwnd, title in winlist if screen_name in title.lower()]
while len(screens) <= 0:
winlist = get_screens()
screens = [(hwnd, title) for hwnd, title in winlist if screen_name in title.lower()]
return screens
winlist = []
windows = get_screensbyname('firefox')
window = windows[0][0]
wRect = win32gui.GetWindowRect(window)
cRect = win32gui.GetClientRect(window)
print('GetWindowRect ', wRect)
print('GetCLientRect ', cRect)

如果窗口在第一个屏幕上,它会输出

GetWindowRect (-7, -7, 1374, 878)
GetCLientRect (0, 0, 1368, 878)

如果窗口在第二个屏幕上,它会输出

GetWindowRect (2728, 345, 4664, 1401)
GetCLientRect (0, 0, 1920, 1048)

现在,据我所知,它忽略了监视器上给定的缩放比例。因为如果我手动应用缩放(使用计算器(,第一个输出将更改为

GetWindowRect (-14, -14, 2748, 1756)
GetCLientRect (0, 0, 2736, 1756)

如何应用窗口所在监视器上设置的缩放比例或dpi精度?

我需要它来捕捉内部区域,并将其流式传输到文件或其他屏幕上的

解决方案相对简单,添加以下行

import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(2)

它还可以设置SetProcessDpiAwareness(1(不知道这两者之间的区别。如果有人能解释一下就好了。

注意:这个答案将被设置为明天的解决方案

最新更新