首页 > 解决方案 > Python 激活同名窗口

问题描述

所以我需要做的是定期更改活动窗口,我的问题是它们都具有相同的名称并且使用它们的 HWND 仅适用于第一个窗口。除此之外,我不想每次都插入它的 HWND

import win32gui, time

def main():
    while(1):
        win32gui.SetForegroundWindow(788574)#win2
        side()
        time.sleep(5)

def side():
    while(1):
        win32gui.SetForegroundWindow(3147934)#win1
        main()
        time.sleep(5)

if __name__ == '__main__':
    main()

标签: pythonwindowhwnd

解决方案


要循环浏览选定的窗口,有几个步骤:

  • 使用win32gui.EnumWindows遍历所有打开的窗口
  • 使用win32gui.GetWindowText从窗口中获取标题栏文本
  • 使用win32com.client.DispatchSendKeys激活切换进程
  • 使用win32gui.SetForegroundWindow选择要激活的窗口

这是代码:

import win32com.client as win32
import win32gui
import time

title = "Untitled - Notepad2"  # cycle all windows with this title

def windowEnumerationHandler(hwnd, top_windows):
    top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
    
top_windows = []  # all open windows
win32gui.EnumWindows(windowEnumerationHandler, top_windows)

winlst = []  # windows to cycle through
for i in top_windows:  # all open windows
   if i[1] == title:
      winlst.append(i)
      
for x in range(5):  # cycle 5 times
   for w in winlst:  # each window with selected title
       shell = win32.Dispatch("WScript.Shell")  # set focus on desktop
       shell.SendKeys('%')  # Alt key
       win32gui.SetForegroundWindow(w[0]) # bring to front, activate
       time.sleep(2)  # 2 seconds

推荐阅读