Python之窗口操作之find_window,set_foreground等

在自动化测试过程中,常常需要模拟按键的操作,比如像窗口发送一个按键,实现鼠标点击的功能,在上一篇文章中,我和大家讨论了python文件生成为不依赖与python库的exe文件的方式(需要了解的朋友戳这里),结合上篇的方法,这里和大家分享使用python对窗口进行操作的方法,如果还不明白这个功能的童鞋们,可以结合autoit中的window操作对比理解。

今天就find_window,set_foreground等方法和大家分享,代码如下:

import win32gui
import re, sys

class WindowMgr():
    '''Encapsulates some calls to the winapi for windows management'''
    def __init__(self):
        '''Constructor'''
        self._handle = None
        
    def find_window(self, class_name = None, window_name):
        '''find a window by its window_name'''
        self._handle = win32gui.FindWindow(class_name, window_name)
        
    def __window_enum_callback(self, hwnd, wildcard):
        '''pass to win32gui.EnumWindows() to check all the opened windows'''
        if re.match(wildcard, str(win32gui.GetWindowsText(hwnd))) != None
            self._handle = hwnd    
    
    def find_window_wildcard(self, wildcard):
        self._handle = None
        win32gui.EnumWindows(self.__window_enum_callback, wildcard)
    
    def set_foreground(self):
        '''put the window in the forground'''
        win32gui.SetForegroundWindow(self._handle)
        
def main():
    w = WindowMgr()
    w.find_window_wildcard('.*Hello*.')
    w.set_foreground()
    
if __name__ == '__main__':
    sys.exit(main())

其中win32gui需要大家安装pywin32模块,pywin32模块下载戳这里

感谢阅读,希望能帮到大家!

Published by Windows Live Writer!

原文地址:https://www.cnblogs.com/berlin-sun/p/windowrelatedwithpython.html