实现了一个window下对窗体操作的类,实现的功能如:移动窗体、获取窗体位置和大小、截取窗体图片、坐标转换等。
直接上代码:
# coding=utf-8 import win32con import win32api import win32gui import win32ui from ctypes import * from ctypes import wintypes GetForegroundWindow = windll.user32.GetForegroundWindow GetWindowRect = windll.user32.GetWindowRect SetForegroundWindow = windll.user32.SetForegroundWindow GetWindowText = windll.user32.GetWindowTextA MoveWindow = windll.user32.MoveWindow EnumWindows = windll.user32.EnumWindows class RECT(Structure): _fields_ = [ ('left', c_long), ('top', c_long), ('right', c_long), ('bottom', c_long) ] class POINT(Structure): _fields_ = [ ('x', c_long), ('y', c_long), ] class FormControl(object): def __init__(self): self.win_hd = None self.win_title = '' def bindActiveWindow(self): """ 函数功能:获取当前焦点所在窗口 """ self.win_hd = GetForegroundWindow() def bindWindowByName(self, win_name): """ 函数功能:根据窗体名获取窗体句柄 """ self.win_title = win_name pro_fun_type = CFUNCTYPE(c_bool, c_int, c_long) pro_fun_p = pro_fun_type(self.EnumWindowsProc) EnumWindows(pro_fun_p, None) def getWinRect(self): """ 函数功能:获取窗体的位置和大小 """ if self.win_hd is None: return None rect=RECT() GetWindowRect(self.win_hd,byref(rect)) return rect def toScreenPos(self, x,y): """ 函数功能:将窗体内部坐标转换为相对于显示屏的绝对坐标 """ #未指定窗口,则结束函数 if self.win_hd is None: return None rect=self.getWinRect() #指定的坐标不在窗体内,则结束函数 if x < 0 or y < 0 or x > rect.right or y > rect.bottom: return None pos = POINT() pos.x = x + rect.left pos.y = y + rect.top return pos def toWindowPos(self,x,y): """ 函数功能:将绝对坐标转换成相对于窗体内部坐标 """ if self.win_hd is None: return None rect = self.getWinRect() pos = POINT() pos.x = x - rect.left pos.y = y - rect.top # 指定的坐标不在窗体内,则结束函数 if pos.x < 0 or pos.y < 0 or pos.x > rect.right or pos.y > rect.bottom: return None return pos def WindowActive(self): """ 函数功能:将窗体置前 """ if self.win_hd is None: return None SetForegroundWindow(self.win_hd) def getHWND(self): return self.win_hd def getWinTitle(self): """ 函数功能:获取窗体的标题 """ if self.win_hd is None: return None buffer = create_string_buffer(255,'