利用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))

 

posted @ 2021-06-15 18:54  BruceLong  阅读(2043)  评论(0编辑  收藏  举报