1. 程式人生 > >pythonwin-win32gui 視窗查詢和遍歷

pythonwin-win32gui 視窗查詢和遍歷

#coding=utf-8

__author__ = 'Administrator'

__doc__ = '''
pythonwin中win32gui的用法
本檔案演如何使用win32gui來遍歷系統中所有的頂層視窗,
並遍歷所有頂層視窗中的子視窗
'''

import win32gui
from pprint import pprint

def gbk2utf8(s):
    return s.decode('gbk').encode('utf-8')

def show_window_attr(hWnd):
    '''
    顯示視窗的屬性
    :return:
    '''
    if not hWnd:
        return

    #中文系統預設title是gb2312的編碼
    title = win32gui.GetWindowText(hWnd)
    title = gbk2utf8(title)
    clsname = win32gui.GetClassName(hWnd)

    print '視窗控制代碼:%s ' % (hWnd)
    print '視窗標題:%s' % (title)
    print '視窗類名:%s' % (clsname)
    print ''

def show_windows(hWndList):
    for h in hWndList:
        show_window_attr(h)

def demo_top_windows():
    '''
    演示如何列出所有的頂級視窗
    :return:
    '''
    hWndList = []
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)
    show_windows(hWndList)

    return hWndList

def demo_child_windows(parent):
    '''
    演示如何列出所有的子視窗
    :return:
    '''
    if not parent:
        return

    hWndChildList = []
    win32gui.EnumChildWindows(parent, lambda hWnd, param: param.append(hWnd),  hWndChildList)
    show_windows(hWndChildList)
    return hWndChildList


hWndList = demo_top_windows()
assert len(hWndList)

parent = hWndList[20]
#這裡系統的視窗好像不能直接遍歷,不知道是否是許可權的問題
hWndChildList = demo_child_windows(parent)

print('-----top windows-----')
pprint(hWndList)

print('-----sub windows:from %s------' % (parent))
pprint(hWndChildList)