利用python+win32api獲取標題對應的視窗控制代碼id,並且操作為當前活動視窗
阿新 • • 發佈:2021-06-15
# #!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021-06-15 18:08 # @Author : BruceLong # @FileName: switch_win.py # @Email : [email protected] # @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 inhwnd_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))