如何使用Python/PyQT/Win32获取Windows任务栏的高度
我想让我的图形界面程序在Windows上对齐到屏幕的右下角。当任务栏没有隐藏的时候,我的程序就会直接盖在任务栏上!
在使用Python/PyQT/Win32的时候,我该怎么做:
- 检查任务栏的自动隐藏功能是否开启
- 获取任务栏的高度
4 个回答
你可以使用 QDesktopWidget
来获取系统屏幕的信息,并从总屏幕区域中减去工作区域。
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
dw = app.desktop() # dw = QDesktopWidget() also works if app is created
taskbar_height = dw.screenGeometry().height() - dw.availableGeometry().height()
不过,如果任务栏在屏幕的侧边,这样做会返回零,这样就没什么用处了。为了解决这个问题,可以通过比较 screenGeometry()
和 availableGeometry()
的差异,来找出任务栏的大小(以及其他保留的空间)。
当任务栏设置为自动隐藏时,available geometry 不会考虑任务栏的大小。
正如David Heffernan提到的,你可以使用GetMonitorInfo
配合pywin32
来获取显示器的大小。特别是,工作区域的大小会排除任务栏的部分。
要获取工作区域的大小(桌面减去任务栏):
from win32api import GetMonitorInfo, MonitorFromPoint
monitor_info = GetMonitorInfo(MonitorFromPoint((0,0)))
work_area = monitor_info.get("Work")
print("The work area size is {}x{}.".format(work_area[2], work_area[3]))
工作区域的大小是1366x728。
要获取任务栏的高度:
from win32api import GetMonitorInfo, MonitorFromPoint
monitor_info = GetMonitorInfo(MonitorFromPoint((0,0)))
monitor_area = monitor_info.get("Monitor")
work_area = monitor_info.get("Work")
print("The taskbar height is {}.".format(monitor_area[3]-work_area[3]))
任务栏的高度是40。
解释
首先,我们需要创建一个句柄来引用主显示器。主显示器的左上角总是位于0,0这个位置,所以我们可以使用:
primary_monitor = MonitorFromPoint((0,0))
我们通过GetMonitorInfo()
获取显示器的信息。
monitor_info = GetMonitorInfo(primary_monitor)
# {'Monitor': (0, 0, 1366, 768), 'Work': (0, 0, 1366, 728), 'Flags': 1, 'Device': '\\\\.\\DISPLAY1'}
显示器的信息会以dict
的形式返回。前两个条目代表显示器的大小和工作区域的大小,都是以元组的形式给出(x坐标,y坐标,高度,宽度)。
work_area = monitor_info.get("Work")
# (0, 0, 1366, 728)
我觉得你需要调用 GetMonitorInfo 来获取你感兴趣的显示器的信息。接着,你需要从 MONITORINFO.rcWork 中读取工作区域。这一步会把显示器上留给任务栏和其他保留区域的部分排除在外。
我认为你不需要担心自动隐藏的问题,因为 GetMonitorInfo 会考虑到这一点。换句话说,当自动隐藏功能开启时,工作区域的大小会等于显示器的总区域。