Python 激活 windows 同名

Python activate windows with the same name

所以我需要做的是定期更改活动 window,我的问题是它们都具有相同的名称并且使用它们的 HWND 仅适用于第一个 window。除此之外,我不想每次都插入它的 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()

要循环 selected windows,需要几个步骤:

  • 使用win32gui.EnumWindows遍历所有打开的windows
  • 使用win32gui.GetWindowText从window
  • 获取标题栏文本
  • 使用win32com.client.DispatchSendKeys激活切换过程
  • 使用win32gui.SetForegroundWindow到selectwindow激活

代码如下:

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