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

这段代码使用Python的win32库遍历并关闭具有特定标题('LicenseInformation')的窗口,无论窗口是否可见。它首先定义了一个枚举窗口的回调函数,然后调用EnumWindows进行遍历,对符合条件的窗口发送WM_CLOSE消息来关闭它们。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

符合条件的,关闭窗口

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值