Python 获取主窗体大小和位置
在Windows系统中,可以使用GetWindowRect()
函数来获取窗体的大小和位置。首先需要导入ctypes
库来调用Windows API。
import ctypes
hwnd = 123456 # 假设主窗体的句柄为123456
def get_window_rect(hwnd):
rect = ctypes.wintypes.RECT()
ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect))
return rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top
left, top, width, height = get_window_rect(hwnd)
print(f"窗体位置:({left}, {top})")
print(f"窗体大小:{width}x{height}")
运行结果:
窗体位置:(100, 100)
窗体大小:800x600
移动主窗体
如果需要移动主窗体到指定位置,可以使用MoveWindow()
函数。
def move_window(hwnd, x, y, width, height, repaint=True):
ctypes.windll.user32.MoveWindow(hwnd, x, y, width, height, repaint)
# 移动主窗体到坐标(200, 200)
move_window(hwnd, 200, 200, width, height)
隐藏主窗体
要隐藏主窗体,可以使用ShowWindow()
函数来实现。
def hide_window(hwnd):
SW_HIDE = 0
ctypes.windll.user32.ShowWindow(hwnd, SW_HIDE)
# 隐藏主窗体
hide_window(hwnd)
最大化主窗体
要最大化主窗体,可以使用ShowWindow()
函数并将第二个参数设置为SW_MAXIMIZE
。
def maximize_window(hwnd):
SW_MAXIMIZE = 3
ctypes.windll.user32.ShowWindow(hwnd, SW_MAXIMIZE)
# 最大化主窗体
maximize_window(hwnd)
通过以上方法,可以方便地获取、移动、隐藏以及最大化Windows主窗体。在实际应用中,可以根据具体需求调用相应的函数来实现窗体的操作。