微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

利用python+win32api获取标题对应的窗口句柄id,并且操作为当前活动窗口

# #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021-06-15 18:08
# @Author : BruceLong
# @FileName: switch_win.py
# @Email   : 18656170559@163.com
# @Software: PyCharm
# @Blog :http://www.cnblogs.com/yunlongaimeng/
import ctypes
import win32gui

import win32con


def get_jb_id(title):
    '''
    根据标题找句柄
    :param title: 标题
    :return:返回句柄所对应的ID
    '''
    jh = []
    hwnd_title = dict()

    def get_all_hwnd(hwnd, mouse):
        if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
            hwnd_title.update({hwnd: win32gui.GetwindowText(hwnd)})

    win32gui.EnumWindows(get_all_hwnd, 0)
    for h, t in hwnd_title.items():
        if t is not "":
            if title in t:
                jh.append(h)

    if len(jh) == 0:
        print("找不到相应的句柄")
    else:
        return jh


def switch_roles(hwnd):
    '''
    根据句柄id切换活动窗口
    :param hwnd: 
    :return: 
    '''
    try:
        ctypes.windll.user32.SwitchToThisWindow(hwnd, True)
        win32gui.ShowWindow(hwnd, win32con.SW_SHOWnorMAL)
        win32gui.SetForegroundWindow(hwnd)
        msg = [True, 'exec success', None]
    except Exception as e:
        msg = [False, '没有找到可操作的对象', str(e)]
    return msg


jb_id_list = get_jb_id("Studio 3T for MongoDB - TRIAL LICENSE")
jb_id = jb_id_list[0] if jb_id_list else jb_id_list
print(switch_roles(jb_id))

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐