【问题标题】:Python activate windows with the same namePython 激活同名窗口
【发布时间】:2020-09-09 20:22:21
【问题描述】:

所以我需要做的是定期更改活动窗口,我的问题是它们都具有相同的名称并且使用它们的 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()

【问题讨论】:

  • 当你说相同的名字时,你的意思是标题栏中的文本相同?
  • 没错,他们都有相同的文字,我试过用他们的 HWND 但还是不行

标签: python window hwnd


【解决方案1】:

要在选定的窗口中循环,有几个步骤:

  • 使用 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

【讨论】:

  • 嘿,非常感谢。以您提供的代码为例,我已经能够做到,感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 2021-08-06
  • 2018-04-19
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多