当前位置: 首页 > 工具软件 > PythonWin > 使用案例 >

python win32gui 遍历所有窗口 根据标题获取句柄 关闭这个标题的窗口 遍历窗口 获取句柄

顾池暝
2023-12-01

首先遍历所有窗口句柄,再提取有标题的窗口

符合条件的,关闭窗口

2023年3月6日 星期一 更新
不管是否可见,都关掉

 def winEnumHandler(hwnd, ctx):
            #if win32gui.IsWindowVisible(hwnd):
            if 'License Information' in win32gui.GetWindowText(hwnd):
                print(hwnd, win32gui.GetWindowText(hwnd))
                win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

        win32gui.EnumWindows(winEnumHandler, None)
        def winEnumHandler(hwnd, ctx):
            if win32gui.IsWindowVisible(hwnd):
                if 'License Information' in win32gui.GetWindowText(hwnd):
                    print(hwnd, win32gui.GetWindowText(hwnd))
                    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

        win32gui.EnumWindows(winEnumHandler, None)

参考
https://stackoverflow.com/questions/55547940/how-to-get-a-list-of-the-name-of-every-open-window

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from win32gui import *
import win32con, os, time, subprocess

p = subprocess.Popen(r"E:\code\dock_project\tampermonkey\run.bat", creationflags=subprocess.CREATE_NEW_CONSOLE )
time.sleep(30)

title_list = []
def foo(hwnd,mouse):
    titles = {}
    # 去掉下面这句就所有都输出了,但是我不需要那么多
    if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd):
        titles['title'] = GetWindowText(hwnd)
        titles['hwnd'] = hwnd
        # titles.add(GetWindowText(hwnd))
    if titles:
        if titles.get('title') == 'ping baidu':
            pass
            title_list.append(titles)


EnumWindows(foo, 0)

print(title_list)
for title in title_list:
    print(title.get('title'))
    hwnd = title.get('hwnd')
    print(hwnd)
    #关闭窗口
    PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

 类似资料: